-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathpc.js
More file actions
executable file
·3922 lines (3774 loc) · 168 KB
/
pc.js
File metadata and controls
executable file
·3922 lines (3774 loc) · 168 KB
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
#!/usr/bin/env node
/**
* @fileoverview Implements the PCjs machine command-line interface
* @author Jeff Parsons <Jeff@pcjs.org>
* @copyright © 2012-2025 Jeff Parsons
* @license MIT <https://www.pcjs.org/LICENSE.txt>
*
* This file is part of PCjs, a computer emulation software project at <https://www.pcjs.org>.
*
* Test examples:
*
* cd disks
* diskimage.js /diskettes/pcx86/sys/dos/compaq/3.31/COMPAQ-DOS331-REVG-720K-DISK1.json --extract --dest=compaq331
* diskimage.js /diskettes/pcx86/sys/dos/compaq/3.31/COMPAQ-DOS331-REVG-720K-DISK2.json --extract --dest=compaq331
* diskimage.js /diskettes/pcx86/sys/dos/compaq/3.31/COMPAQ-DOS331-REVG-720K-DISK3.json --extract --dest=compaq331
* for ((t=1; t<=99; t++)); do pc.js compaq331 "load info;chkdsk" --drivetype=$t --sys=compaq:3.31g --test; if [ $? -ne 0 ]; then break; fi; done
*/
import DataBuffer from "../../machines/modules/v2/databuffer.js";
import DbgLib from "../../machines/modules/v2/dbglib.js";
import StrLib from "../../machines/modules/v2/strlib.js";
import Device from "../../machines/modules/v3/device.js";
import CharSet from "../../machines/pcx86/modules/v2/charset.js";
import DiskInfo from "../../machines/pcx86/modules/v3/diskinfo.js";
import { MAXDEBUG, globals } from "../../machines/modules/v3/defines.js";
import MESSAGE from "../../machines/modules/v3/message.js";
import WebIO from "../../machines/modules/v3/webio.js";
import DiskLib from "../modules/disklib.js";
import PCJSLib from "../modules/pcjslib.js";
import { node } from "../modules/nodeapi.js";
await node.import("child_process", "fs", "glob", "json5", "path", "xml2js");
let device = new Device("node");
let printf = device.printf.bind(device);
let sprintf = device.sprintf.bind(device);
let diskLib = new DiskLib(device);
let rootDir, pcjsDir;
let configFile = "pc.json5";
let configJSON = {}, machines = null;
/**
* @class {PC}
*/
export default class PC extends PCJSLib {
bare = false; // true if --bare specified
debug = false; // true if --debug specified
halt = false; // true if --halt specified
floppy = false; // true if --floppy specified
bootSector = "";
bootSelect = "";
serial = false; // true if --serial specified
useSerial = false;
normalize = false; // true if --normalize specified
test = false; // true if --test specified
verbose = false; // true if --verbose specified
autoStart = false;
training = 4; // training message count
machineType = "pcx86";
systemType = "msdos";
systemVersion = "3.30";
systemMBR = "pcjs.mbr";
savedMachine = "compaq386.json";
savedState = "state386.json";
localMachine = ""; // current machine config file
localDir = "."; // local directory used to build localDisk
localDisk = "harddisk.json";
localDiskette = "floppy.json";
diskLabel = "default";
machineDrive = ""; // current drive *inside* the machine
machineDir = ""; // current directory *inside* the machine
maxFiles = 1024; // default disk file limit
kbTarget = 10 * 1024; // default disk capacity, in kilobytes (Kb)
shutdown = false;
messages = false; // true if --messages specified
messagesFilter; debugMode;
prompt = ">"; command = ""; commandPrev = "";
machine = "test"; // TODO: Remove after testing
Component; Errors; Interrupts; Web; embedMachine;
diskItems = [];
diskIndexCache = null; diskIndexKeys = [];
fileIndexCache = null; fileIndexKeys = [];
/**
* Each entry in drives[] is a driveInfo object, created by newDrive().
*/
drives = [];
driveBuild = 0; // by default, the drive we build, if any, will be drive 0
geometryOverride = false;
static functionKeys = {
"ArrowUp": "$up",
"ArrowDown": "$down",
"ArrowRight": "$right",
"ArrowLeft": "$left",
"F1": "$f1",
"F2": "$f2",
"F3": "$f3",
"F4": "$f4",
"F5": "$f5",
"F6": "$f6",
"F7": "$f7",
"F8": "$f8",
"F9": "$f9",
"F10": "$f10",
"F11": "$f11",
"F12": "$f12",
"\u001b[A": "$up",
"\u001b[B": "$down",
"\u001b[C": "$right",
"\u001b[D": "$left",
"\u001bOP": "$f1",
"\u001bOQ": "$f2",
"\u001bOR": "$f3",
"\u001bOS": "$f4",
"\u001b[15~": "$f5",
"\u001b[17~": "$f6",
"\u001b[18~": "$f7",
"\u001b[19~": "$f8",
"\u001b[20~": "$f9",
"\u001b[21~": "$f10",
"\u001b[23~": "$f11",
"\u001b[24~": "$f12"
};
static optionMap = {
'?': "help",
'b': "bare",
'c': "commands",
'd': "debug",
'f': "floppy",
'h': "halt",
'l': "local",
'n': "normalize",
's': "serial",
't': "test",
'v': "verbose"
};
/**
* PC()
*
* @this {PC}
* @param {string} [idTerminal]
* @param {string} [sCommands]
*/
constructor(idTerminal, sCommands = "")
{
super();
let pc = this;
this.commands = sCommands;
this.machine = this.newMachine();
this.onTerminalData = null;
this.terminalEncoding = "";
this.terminalRawMode = false;
if (idTerminal) {
this.terminal = document.querySelector('#' + idTerminal);
if (this.terminal) {
device.addBinding(WebIO.BINDING.PRINT, this.terminal, this.onTerminalInput.bind(this));
node.process.stdin = {
resume: function() {},
setEncoding: function(encoding) {
pc.terminalEncoding = encoding;
},
setRawMode: function(rawMode) {
pc.terminalRawMode = rawMode;
},
on: function(event, fn) {
if (event == "data") {
pc.onTerminalData = fn;
}
}
};
}
this.main(...PC.mapArgs(PC.optionMap)).catch((err) => {
printf("exception: %s\n", err.message);
});
}
}
/**
* onTerminalInput(event, down)
*
* @this {PC}
* @param {Event} event
* @param {boolean} [down] (true if keydown, false if keyup, undefined if keypress)
* @returns {boolean} (true to consume the event, false to pass it on)
*/
onTerminalInput(event, down)
{
if (this.onTerminalData && this.terminalRawMode) {
let data;
if (event.type == "keydown") {
switch(event.key) {
case "Backspace":
case "Delete":
data = "\b";
break;
case "Enter":
data = "\r";
break;
case "Escape":
data = "\x1b";
break;
case "Tab":
data = "\t";
break;
case "Control":
case "Shift":
case "Alt":
case "Meta":
break;
default:
if (event.ctrlKey) {
if (event.key >= "a" && event.key <= "z") {
data = String.fromCharCode(event.key.charCodeAt(0) - 96);
}
break;
}
if (event.altKey || event.metaKey) break;
data = event.key;
break;
}
} else if (event.type == "keypress") {
data = event.key;
}
if (data) {
this.onTerminalData(data);
return true;
}
}
return false;
}
/**
* setDebugMode(nEvent, dataEvent)
*
* @this {PC}
* @param {number} nEvent (eg, DbgLib.EVENTS.EXIT (0), DbgLib.EVENTS.ENTER (1), DbgLib.EVENTS.READY (2))
* @param {number} [dataEvent] (non-zero if debugger is stepping; we want to avoid unnecessary output in that case)
*/
setDebugMode(nEvent, dataEvent)
{
/**
* Once the user has been sufficiently trained, we no longer display the helpful "training" messages.
*/
let message = this.training > 0 && !dataEvent;
let prevMode = this.debugMode;
if (!nEvent && this.debugMode != nEvent) {
if (message && !this.test) {
printf("[Press CTRL-D to enter command mode]\n");
this.training--;
}
}
this.debugMode = nEvent;
if (this.debugMode == DbgLib.EVENTS.READY && prevMode != DbgLib.EVENTS.READY) {
this.command = "";
if (message) {
printf('[' + (this.commandPrev? "Press CTRL-A to repeat last command" : "Type help for list of commands") + ", CTRL-C to terminate]\n");
this.training--;
}
printf("%s> ", this.prompt);
}
}
/**
* convertXML(xml, idAttrs)
*
* @this {PC}
* @param {Object} xml
* @param {string} [idAttrs]
* @returns {Object} (JSON-style machine configuration)
*/
convertXML(xml, idAttrs = '@')
{
let machine = {};
/**
* Walk the XML tree and add all the objects to the root of the machine object.
*/
let addXML = function(xml, xid, obj, oid) {
if (!obj || obj == machine) {
obj = {};
if (!oid) oid = xid;
}
if (oid) {
if (!machine[oid]) {
machine[oid] = obj;
} else {
if (Array.isArray(machine[oid])) {
machine[oid].push(obj);
} else {
machine[oid] = [machine[oid], obj];
}
}
}
xml = xml[xid];
if (typeof xml != "object") {
obj['value'] = xml;
return;
}
for (let key in xml) {
if (key == idAttrs) {
/**
* Our XSL files include rules for providing default IDs, so we do, too...
*/
if (!xml[key]['id']) {
obj['id'] = oid;
}
addXML(xml, key, obj);
} else {
if (key == 'br' || key == 'comment' || key == 'control' || key == 'menu') {
continue;
}
if (Array.isArray(xml[key])) {
for (let i = 0; i < xml[key].length; i++) {
addXML(xml[key], i, machine, key);
}
} else {
if (key != '_') {
obj[key] = xml[key];
} else {
obj['value'] = xml[key];
}
}
}
}
};
addXML(xml, 'machine');
return machine;
}
/**
* loadModules(factory, modules, done)
*
* @this {PC}
* @param {string} factory
* @param {Array.<string>} modules
* @param {function()} done
*/
async loadModules(factory, modules, done)
{
let pc = this;
for (let modulePath of modules) {
/**
* Unless I replace all backslashes in modulePath with forward slashes; eg:
*
* .replace(/\\/g, '/')
*
* Node will fail on Windows operating systems with the following error:
*
* TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module
* "..\..\..\machines\modules\v2\defines.js" is not a valid package name ....
*
* which seems bizarre, since backslash is actually Windows' preferred path separator
* and is precisely what Node's path.sep returns on Windows. ¯\_(ツ)_/¯
*
* Moreover, we cannot join modulePath with rootDir, because rootDir will start with
* a drive letter (eg, "C:") on Windows, which then fails with the following error:
*
* Only URLs with a scheme in: file and data are supported by the default ESM loader.
* On Windows, absolute paths must be valid file:// URLs. Received protocol 'c:'
*
* so we join it with a relative directory instead (ie, "../..").
*/
modulePath = node.path.join("../..", modulePath).replace(/\\/g, '/');
if (this.debug) printf("loading: %s\n", modulePath.replace(/\.\.\/\.\.\//g, '/'));
let name = node.path.basename(modulePath, ".js");
if (name == "embed") {
let { [factory]: embed } = await import(modulePath);
this.embedMachine = embed;
continue;
}
let module = await import(modulePath);
/**
* Below are the set of classes that we need access to (eg, their static methods, constants, etc).
*/
switch(name) {
case "component":
this.Component = module.default;
/**
* We override Component.printf() in order to replace its DEBUG check with our own debug check.
*/
this.Component.printf = function(format, ...args) {
let bitsMessage = 0;
if (typeof format == "number") {
bitsMessage = format;
format = args.shift();
}
if (pc.Component.testBits(bitsMessage, MESSAGE.ERROR)) {
format = "error: " + format + "\n";
bitsMessage = 0;
}
if (pc.Component.testBits(bitsMessage, MESSAGE.WARNING)) {
format = "warning: " + format + "\n";
bitsMessage = 0;
}
if (pc.debug || !bitsMessage) {
printf(format, ...args);
}
};
break;
case "defines":
/**
* Whereas OUR "globals.browser" value reflects whether WE are running in a browser, we always
* want the machine's "globals.browser" value to indicate that it is NOT running in a browser, so that
* Component.getElementsByClass() will always build fake HTML elements for the machine's initialization.
*/
module.globals.browser = false;
break;
case "errors":
this.Errors = module.default;
break;
case "interrupts":
this.Interrupts = module.default;
break;
case "weblib":
this.Web = module.default;
break;
}
/**
* If there's any chance that the module might print something, add a function to intercept it.
*/
if (module.default && module.default.prototype) {
module.default.prototype.print = function print(s, bitsMessage) {
if ((pc.debugMode || !pc.autoStart) && !bitsMessage || (bitsMessage || pc.messages) && pc.Component.testBits(pc.messagesFilter, bitsMessage)) {
printf(s);
}
};
}
}
done();
}
/**
* initMachine(args)
*
* @this {PC}
* @param {string} args
*/
initMachine(args)
{
let machine = this.machine;
let Component = this.Component;
let Interrupts = this.Interrupts;
try {
/**
* Simulate the "web page" embedding and initialization process now.
*/
this.embedMachine(machine.id, null, null, args);
this.Web.doPageInit();
/**
* Get the CPU component so we can keep tabs on its running state and also hook
* a few interrupts (eg, INT 0x10). Get the Debugger component so we can override
* the debugger's print() function.
*/
machine.cpu = Component.getComponentByType("CPU");
if (machine.cpu && machine.cpu.addIntNotify && Interrupts) {
machine.cpu.addIntNotify(Interrupts.VIDEO, this.intVideo.bind(this));
machine.cpu.addIntNotify(Interrupts.VIDEO_VGA, this.intVideoVGA.bind(this));
machine.cpu.addIntNotify(Interrupts.DISK, this.intDisk.bind(this));
machine.cpu.addIntNotify(Interrupts.BOOTSTRAP, this.intReboot.bind(this));
machine.cpu.addIntNotify(Interrupts.DOS_EXIT, this.intLoad.bind(this));
}
/**
* Get the FDC component so we can query its list of available diskettes,
* and get the HDC component so we can get the state of its hard drive(s).
*/
machine.fdc = Component.getComponentByType("FDC");
machine.hdc = Component.getComponentByType("HDC");
/**
* Get the Debugger component so we can receive debugger events and send
* debugger commands.
*/
machine.dbg = Component.getComponentByType("Debugger");
if (machine.dbg) machine.dbg.onEvent(this.setDebugMode.bind(this));
/**
* Get the Keyboard component to get access to injectKeys(), which simplifies the
* injection of keystrokes into the machine.
*/
machine.kbd = Component.getComponentByType("Keyboard");
/**
* Establish a serial connection for console I/O if --serial was specified OR there's
* no keyboard device (as in the case of our PDP-11 machines).
*/
if (this.serial || !machine.kbd) {
machine.serial = Component.getComponentByType("SerialPort");
if (machine.serial) {
let exports = machine.serial['exports'];
if (exports) {
/**
* The PDP-11 serial.js component exports a "setConnection" function, whereas the
* PC serial.js component exports a "bind" function. TODO: Bring the PDP-11 and PC
* serial interfaces into alignment.
*/
let fnSetConnection = exports['bind'] || exports['setConnection'];
if (fnSetConnection) {
if (fnSetConnection.call(machine.serial, this, this.receiveSerial)) {
machine.fnSendSerial = exports['receiveData'];
}
}
}
}
}
/**
* Since there may be no debugger (and even if there is, machines that are auto-started won't
* trigger any debugger events), we simulate an appropriate event.
*
* NOTE: The test here used to be "machine.cpu && machine.cpu.isRunning()", but if you're not using
* the --local option, the CPU may not up and running yet, so we rely on the autoStart setting instead.
*/
this.setDebugMode(machine.cpu && this.autoStart? DbgLib.EVENTS.EXIT : DbgLib.EVENTS.READY);
}
catch(err) {
printf("machine initialization error: %s\n", err.message);
}
}
/**
* intVideo(addr)
*
* Notification handler for all INT 0x10 software interrupts.
*
* @this {PC}
* @param {number} addr
* @returns {boolean} true to proceed with the INT 0x10 software interrupt, false to skip
*/
intVideo(addr)
{
let count = 1, s;
let maxRows = 25, maxCols = 80; // TODO: update these to reflect active video mode
let machine = this.machine, cpu = machine.cpu;
let CX = (cpu.regECX & 0xffff);
let AH = ((cpu.regEAX >> 8) & 0xff), AL = (cpu.regEAX & 0xff);
let DH = ((cpu.regEDX >> 8) & 0xff), DL = (cpu.regEDX & 0xff);
if (machine.nestedVideo) { // some BIOSes issue calls within the "write TTY" (0x0E)
return true; // function, and we want to ignore those
}
switch (AH) {
case 0x00:
machine.rowCursor = machine.colCursor = 0;
break;
case 0x02: // set cursor position (row=DH, col=DL)
if (DL >= maxCols || DH >= maxRows) {
break; // ignore "off-screen" positions
}
if (DH > machine.rowCursor || DH < machine.rowCursor && DL < machine.colCursor) {
printf('\n');
}
else if (DH == machine.rowCursor) {
if (DL < machine.colCursor) {
if (!DL) {
printf('\r');
} else {
let s = "";
while (DL + s.length < machine.colCursor) {
s += '\b';
}
printf(s);
}
}
else if (DL > machine.colCursor) {
/**
* When BASIC/BASICA erases a character (in response to a BS/DEL key), it wants to redraw
* the entire line (eg, with spaces if there was nothing past the character being deleted);
* in that situation, it seems best (well, certainly easiest) to simply ignore the cursor
* updates and let the spaces ("chips") fall where they may.
*/
break;
}
}
machine.rowCursor = DH;
machine.colCursor = DL;
break;
case 0x06: // scroll up (AL lines)
while (AL--) { // TODO: Should probably check the boundaries of the scroll
printf('\n'); // but that's more work than our cheesy TTY emulation deserves
}
break;
case 0x09: // write raw char/attr (AL/BL) with count (CX)
case 0x0A: // write raw char (AL) with count (CX)
/**
* NOTE: I don't think the IBM BIOS handled CX == 0 very well (it looped 65536 times instead),
* so we're not going to emulate/risk that. Also, this function isn't supposed to move the
* cursor, but when it's used with a count of 1, the caller usually plans to move the cursor
* themselves anyway, so we assume they will; otherwise, we should "backspace" an equal number
* of times afterward.
*/
count = CX || 1;
if (count != 1) {
// printf("%s%s", s.repeat(count), "\b".repeat(count));
break;
}
/* falls through */
case 0x0E: // write TTY char (AL)
/**
* By default, fromCP437() does NOT translate control characters to UTF-8, which is the proper
* thing to do for TTY control characters (ie, BEL, BS, LF, and CR) that the TTY function (0x0E)
* wants to handle, but all other characters must be translated (including ESC or 0x1B, which
* BASIC uses to display a left-arrow symbol).
*/
s = CharSet.fromCP437(AL, AH != 0x0E || [0x07, 0x08, 0x0A, 0x0D].indexOf(AL) < 0);
printf("%s", s.repeat(count));
if (s == '\r') {
machine.colCursor = 0;
} else if (s == '\n') {
while (machine.rowCursor < maxRows && count--) {
machine.rowCursor++;
}
} else if (s == '\b') {
while (machine.colCursor > 0 && count--) {
machine.colCursor--;
}
} else {
while (machine.colCursor < maxCols && count--) {
machine.colCursor++;
}
}
break;
}
/**
* Originally, we only hooked the IRET if a TTY function (0x0E) was being performed, because that
* was the only time we wanted to ignore nested INT 0x10 calls, but since we're also handling INT 0x6D
* calls now (so that we don't miss video calls trigged by CALLF), we need to hook the IRET every time.
*/
machine.nestedVideo++; // TTY function performs nested cursor control calls (eg, AH=0x02)
cpu.addIntReturn(addr, function onVideoReturn(nLevel) {
machine.nestedVideo--;
});
return true;
}
/**
* intVideoVGA(addr)
*
* Notification handler for all INT 0x6D software interrupts.
*
* Assuming you're using an IBM VGA, its BIOS initializes vector 6Dh to the VGA BIOS entry point,
* and then it initializes vector 10h to issue INT 0x6D followed by an IRET.
*
* The ONLY reason we intercept this is to support newer versions of DOS (eg, PC DOS 6.x and 7.x),
* which decided to use PUSHF/CALLF to call BIOS video functions instead of a normal INT 10h. Since
* our intVideo() handler will ignore nested calls, it will ignore any INT 0x6D that was generated by
* an INT 0x10, but it will NOT ignore calls that were triggered by CALLF.
*
* Other more resilient ways to avoid the PUSHF/CALLF problem would be to patch the BIOS or install
* our own handler somewhere in the machine's memory, but obviously that's more work, whereas so far,
* I've managed to maintain a completely non-invasive solution. The PCjs debugger also supports
* execution breakpoints that are non-invasive (similar to how the 80386 debug registers work), so I
* could tap into that functionality, but that's also a bit messy (and more work).
*
* @this {PC}
* @param {number} addr
* @returns {boolean} true to proceed with the INT 0x6D software interrupt, false to skip
*/
intVideoVGA(addr)
{
return this.intVideo(addr);
}
/**
* intDisk(addr)
*
* @this {PC}
* @param {number} addr
* @returns {boolean} true to proceed with the INT 0x13 software interrupt, false to skip
*/
intDisk(addr)
{
if (this.geometryOverride) {
let cpu = this.machine.cpu;
/**
* We do basically the same thing our custom MBR does: build drive tables in unused
* interrupt vector space (16 bytes spanning vectors 0xC0 to 0xC3 for drive 0, and 16
* bytes spanning vectors 0xC4 to 0xC7 for drive 1) and then update the drive table
* address at vector 0x41 and/or 0x46 as appropriate.
*
* I don't relish altering the machine state like this (using the custom MBR is much
* cleaner and should actually be compatible with real hardware), but in order to ALSO
* test the operating system's ability to initialize and format drives with custom
* geometries from scratch, this seems the best alternative.
*/
for (let i = 0; i <= 1; i++) {
if (!this.drives[i]) break;
if (this.drives[i].drivetype == 0) {
let vec = 0xC0 + i * 4;
for (let off = 0; off < 16; off++) {
let b = 0;
switch(off) {
case 0x00:
b = this.drives[i].nCylinders & 0xff;
break;
case 0x01:
b = (this.drives[i].nCylinders >> 8) & 0xff;
break;
case 0x02:
b = this.drives[i].nHeads;
break;
case 0x0E:
b = this.drives[i].nSectors;
break;
}
cpu.setByte(vec * 4 + off, b);
}
vec = (i == 0)? 0x41 : 0x46;
cpu.setShort(vec * 4, (0xC0 + i * 4) * 4);
cpu.setShort(vec * 4 + 2, 0);
}
}
this.geometryOverride = false;
}
return true;
}
/**
* intReboot(addr)
*
* @this {PC}
* @param {number} addr
* @returns {boolean} true to proceed with the INT 0x19 software interrupt, false to skip
*/
intReboot(addr)
{
/**
* An INT 19h issued from our own QUIT.COM is a signal to shut down.
*/
let cpu = this.machine.cpu;
if (cpu.getIP() == 0x102) {
let sig = cpu.getSOWord(cpu.segCS, cpu.getIP()+2) + (cpu.getSOWord(cpu.segCS, cpu.getIP()+4) << 16);
if (sig == 0x534A4350) { // "PCJS"
let getString = function(seg, off, len) {
let s = "";
while (len--) {
let b = cpu.getSOByte(seg, off++);
if (!b) break;
s += CharSet.fromCP437(b);
}
return s;
};
let len = cpu.getSOByte(cpu.segDS, 0x80);
let args = getString(cpu.segDS, 0x81, len).trim();
if (!args) { // if there were no arguments, then simply "quit"
this.exit(0);
return false;
}
if (args.toLowerCase() != "/r") {
printf("unrecognized option: %s\n", args);
return false; // for any unrecognized option, returning false will skip the INT 19h
} // otherwise, for "QUIT /R", we simply reboot
printf("rebooting...\n");
}
}
/**
* Any other INT 19h should proceed normally; however, if the machine's hard drive(s) are using
* custom geometries AND we didn't build a drive image with our custom MBR, then the drive table(s)
* for those geometries will never get loaded into memory. So we take this opportunity to install
* them before the boot process begins.
*
* Unfortunately, the default INT 19h behavior resets ALL drive table vectors, so if we tried to
* install our own drive tables now, they would immediately be replaced. So instead we set a flag
* (geometryOverride) telling our intDisk() handler to install new table(s) on the next INT 13h call.
*/
if (this.drives[0].driveType == 0 || this.drives[1] && this.drives[1].driveType == 0) {
this.geometryOverride = true;
}
/**
* Also, in order to test floppy diskettes with non-standard sector sizes, we take this opportunity
* to patch the Diskette Parameter Table (DPT) if we're booting a floppy with a non-standard sector size.
* Since this table will generally be in ROM (well, at least on the first reboot, since no other code
* will have had an opportunity to copy it elsewhere yet), we must use bus.setByteDirect() instead of
* cpu.setByte().
*
* TODO: The "correct" way to deal with this will be to make my own boot sector, similar to the MBR I
* wrote to deal with custom hard disk geometries. It should be a trivial change, since most DOS boot
* sectors already copy the DPT to RAM in order tweak other non-geometric parameters (eg, stepping rate).
*/
if (!this.drives[0].partitioned && this.drives[0].cbSector && this.drives[0].cbSector != 512) {
let fpDPT = cpu.getLong(0x1E * 4); // get the DPT address from interrupt vector 0x1E
let addrDPT = ((fpDPT >>> 16) << 4) + (fpDPT & 0xffff); // convert real-mode far pointer to physical address
/**
* The 4th byte in the DPT (at offset 3) indicates the # bytes/sector, and it is stored as a shift
* count for the base sector size of 128 (128 << 0 = 128, 128 << 1 = 256, 128 << 2 == 512, etc). So
* the value to write is log2(cbSector) - log2(128). We also update the EOT value in the 5th byte
* (at offset 4), but that appears to be less critical.
*/
cpu.bus.setByteDirect(addrDPT + 3, Math.log2(this.drives[0].cbSector) - 7);
cpu.bus.setByteDirect(addrDPT + 4, this.drives[0].nSectors);
/**
* Unfortunately, this all seems to be for naught, because while stepping through the MS-DOS 3.30
* initialization code in IO.SYS, I saw that when it loads the entire FAT into the top of available
* memory, it calculates how many paragraphs all the FAT sectors will need, and it does so by shifting
* the FAT sector count left 5 times. Well, that only works for 512-byte sectors, because log2(512)
* is 9 and log2(16) is 4, and 9 - 4 == 5. The code begins at 70:2CA2 (look for the INT 12h memory
* size call).
*
* When I tested MS-DOS 3.30 with a boot floppy formatted 40:2:5:1024, which contained only one FAT
* sector, IO.SYS tried to read that one 1K FAT sector into segment 9FE0. At most, only 512 bytes
* (0x20 paragraphs) could be returned, since there's no RAM at A000, and even if 512 bytes of FAT was
* all IO.SYS needed in order continue loading the operating system, there was a second problem,
* which is that the request spans a 64K DMA boundary, so the call will always return an error.
*
* Well, let's see how far we get if we shave 1K off available RAM. That should at least avoid the
* DMA boundary problem....
*/
let kbRAM = cpu.getShort(0x413);
if (kbRAM % 64 == 0) {
cpu.setShort(0x413, --kbRAM);
}
/**
* So, no, MS-DOS 3.30 is totally broken for non-512-byte sectors, because after it got past reading
* the FAT (into segment 9FA0, thanks to the reduced memory size), it then proceeded to read MSDOS.SYS
* one track at a time, starting 5C9:0, then 5C9:A00, then 5C9:1400, etc. Well, that's great if all 5
* sectors on each track are only 512 bytes, but not so great if they are all 1024 bytes. The address
* for each successive track is calculated by this code (presumably part of the IO.SYS disk driver):
*
* AX=001E BX=0000 CX=0005 DX=0100 SP=06F4 BP=0005 SI=0522 DI=0482
* SS=0000 DS=0070 ES=05C9 PS=0296 V0 D0 I1 T0 S1 Z0 A1 P1 C0
* &0070:0E2E 2BC1 SUB AX,CX ;cycles=5
* >> tr
* AX=0019 BX=0000 CX=0005 DX=0100 SP=06F4 BP=0005 SI=0522 DI=0482
* SS=0000 DS=0070 ES=05C9 PS=0202 V0 D0 I1 T0 S0 Z0 A0 P0 C0
* &0070:0E30 D0E1 SHL CL,1 ;cycles=2
* >> tr
* AX=0019 BX=0000 CX=000A DX=0100 SP=06F4 BP=0005 SI=0522 DI=0482
* SS=0000 DS=0070 ES=05C9 PS=0206 V0 D0 I1 T0 S0 Z0 A0 P1 C0
* &0070:0E32 02F9 ADD BH,CL ;cycles=2
* >> tr
* AX=0019 BX=0A00 CX=000A DX=0100 SP=06F4 BP=0005 SI=0522 DI=0482
* SS=0000 DS=0070 ES=05C9 PS=0206 V0 D0 I1 T0 S0 Z0 A0 P1 C0
* &0070:0E34 EBCC JMP 0E02 ;cycles=2
*
* After a track is read, this code reduces the remaining sector count (AX) by the number of sectors just
* read (CX == 5), then shifts CX left 1 bit (using a byte shift), and then adds that to the HIGH byte of the
* offset for the next read (BX). So it is effectively adding CX * 256 to BX -- or rather # sectors * 512,
* thanks to the earlier shift -- which of course only works for 512-byte sectors.
*
* At this point, it's clear this is a pointless exercise -- at least for MS-DOS 3.30.
*
* UPDATE: I took a quick look at PC DOS 2.0, and its boot sector immediately makes hard-coded assumptions
* about sector size. Here's how it calculates the number of directory sectors from the number of root directory
* entries:
*
* (entries * 32 + 0x1FF) / 0x200
*
* Things go wrong almost immediately, since it has miscalculated where the first data sector (ie, IO.SYS) is
* located. Kind of depressing, since DOS 2.0 *introduced* the BPB, which included a field for sector size....
*/
}
return true;
}
/**
* intLoad(addr)
*
* If an INT 0x20 is followed by a RET and a "PCJS" signature, then it was issued by one
* of our own programs (eg, LOAD.COM).
*
* @this {PC}
* @param {number} addr
* @returns {boolean} true to proceed with the INT 0x20 software interrupt, false to skip
*/
intLoad(addr)
{
let cpu = this.machine.cpu;
let sig = cpu.getSOWord(cpu.segCS, cpu.getIP()+2) + (cpu.getSOWord(cpu.segCS, cpu.getIP()+4) << 16);
if (sig == 0x534A4350) { // "PCJS"
let getString = function(seg, off, len) {
let s = "";
while (len--) {
let b = cpu.getSOByte(seg, off++);
if (!b) break;
s += CharSet.fromCP437(b);
}
return s;
};
let len = cpu.getSOByte(cpu.segDS, 0x80);
let args = getString(cpu.segDS, 0x81, len).trim();
if (cpu.getIP() == 0x102) { // INT 20h appears to have come from LOAD.COM
printf("\n%s\n", this.doLoad(args));
}
else { // INT 20h assumed to come from a hidden PCJS command app (eg, LS.COM)
if (globals.browser) { // if running in a browser, display the same error as the "exec" command
printf("external commands disabled in browser\n");
return true;
}
let pc = this;
let off = cpu.getIP()+6;
let len = cpu.getSOByte(cpu.segDS, off++);
let appName = getString(cpu.segDS, off, len).trim();
//
// Check for newer helper binaries that store both current drive AND current directory into
// the offset stored at offset 0x101; otherwise, we continue with the hard-coded offset of 0x120.
//
off = 0x120;
this.machineDrive = "";
if (cpu.getSOByte(cpu.segDS, 0x100) == 0xBE) {
off = cpu.getSOWord(cpu.segDS, 0x101);
this.machineDrive = String.fromCharCode(0x40 + cpu.getSOByte(cpu.segDS, off++));
}
this.machineDir = getString(cpu.segDS, off, -1);
setTimeout(function() {
pc.doCommand("exec " + appName + " " + args, !!pc.drives[pc.driveBuild].driveManifest);
}, 0);
return false; // returning false should bypass the INT 20h and fall into the JMP $-2;
} // we want the machine to spin its wheels until it has been unloaded/reloaded
}
return true;
}
/**
* getDriveInfo()
*
* @this {PC}
* @returns {string}
*/
getDriveInfo()
{
let text = "\n";
if (this.debug && this.machine.id) {
text += sprintf("%s machine ID %s\n", this.machine.type, this.machine.id);
}
let driveInfo = this.drives[this.driveBuild];
if (driveInfo.driveManifest || driveInfo.driveType >= 0) {
let info = {
controller: driveInfo.driveCtrl,
type: driveInfo.driveType < 0? 0 : driveInfo.driveType,
cylinders: driveInfo.nCylinders,
heads: driveInfo.nHeads,
sectorsPerTrack: driveInfo.nSectors,
sectorSize: driveInfo.cbSector || 512,
clusterSize: driveInfo.clusterSize,
driveSize: driveInfo.driveSize.toFixed(1) + "Mb"
};
text += sprintf("%s drive type %d, CHS %d:%d:%d, %s\n", info.controller, info.type, info.cylinders, info.heads, info.sectorsPerTrack, info.driveSize);
let vol = driveInfo.volume;
if (vol) {
info.sectorSize = vol.cbSector || info.sectorSize;
info.mediaID = sprintf("%#04x", vol.idMedia);
let sectorsFAT = (vol.vbaRoot - vol.vbaFAT);
info.typeFAT = vol.nFATBits || vol.idFAT;
info.totalFATs = (sectorsFAT / Math.ceil(Math.ceil(vol.clusTotal * info.typeFAT / 8) / info.sectorSize))|0;
info.sizeRoot = vol.rootEntries || vol.rootTotal;
info.sectorsHidden = vol.lbaStart;
info.sectorsReserved = vol.vbaFAT;
info.sectorsFAT = (sectorsFAT / info.totalFATs)|0;
info.sectorsRoot = Math.ceil((info.sizeRoot * 32) / info.sectorSize);
info.sectorsTotal = vol.lbaTotal;
info.sectorsData = info.sectorsTotal - info.sectorsReserved - sectorsFAT - info.sectorsRoot;
info.clusterSize = vol.clusSecs * info.sectorSize;
info.clustersTotal = vol.clusTotal;
info.clustersFree = vol.clusFree;
info.bytesTotal = info.clustersTotal * info.clusterSize;
info.bytesFree = info.clustersFree * info.clusterSize;
info.usageFinalFAT = (info.sectorSize - (Math.ceil(info.clustersTotal * info.typeFAT / 8) % info.sectorSize)) / info.sectorSize * 100;
text += sprintf("%d hidden sectors, %d reserved sectors\n", info.sectorsHidden, info.sectorsReserved);
text += sprintf("%d-bit FAT, %d-byte clusters, %d clusters\n", info.typeFAT, info.clusterSize, info.clustersTotal);
text += sprintf("%d FAT sectors (x%d), %d root sectors (%d entries)\n", info.sectorsFAT, info.totalFATs, info.sectorsRoot, info.sizeRoot);
text += sprintf("%d total sectors, %d data sectors, %d data bytes\n", info.sectorsTotal, info.sectorsData, info.bytesTotal);
}
}
return text.trim()? text : "use build to create disk image first\n";
}
/**
* receiveSerial(b)
*
* @this {PC}
* @param {number} b
*/
receiveSerial(b)
{
let s;
if (b != StrLib.ASCII.CR && b != StrLib.ASCII.LF) {
s = StrLib.ASCIICodeMap[b];
}
if (s) {
s = '<' + s + '>';
} else {
s = String.fromCharCode(b);
}
printf(s);
this.useSerial = true;
}