This repository was archived by the owner on Sep 10, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcpm_bdos.go
More file actions
1936 lines (1574 loc) · 51.4 KB
/
cpm_bdos.go
File metadata and controls
1936 lines (1574 loc) · 51.4 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
// This file implements the BDOS function-calls.
//
// These are documented online:
//
// * https://www.seasip.info/Cpm/bdos.html
package cpm
import (
"fmt"
"io"
"io/fs"
"log/slog"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/koron-go/z80"
"github.com/skx/cpmulator/consolein"
"github.com/skx/cpmulator/fcb"
)
// blkSize is the size of block-based I/O operations
const blkSize = 128
// maxRC is the maximum read count
const maxRC = 128
// data2String is a simple helper that is designed to dump a small
// array of data to a string.
//
// It is used to write FCB values and I/O records to logs.
func data2String(data []uint8) (string, string) {
// Ensure we're only dumping a single record
if len(data) > 128 {
panic("too big")
}
// copy into a record just to deal with short reads or writes.
t := make([]uint8, 128)
copy(t, data)
// HEX and ASCII results
hex := ""
asc := ""
// Process each one
for _, e := range t {
hex += fmt.Sprintf("%02X ", e)
if e > 32 && e < 128 {
asc += string(e)
} else {
asc += "."
}
}
// Return
return hex, asc
}
// setResult sets up all four of the registers that we should
// return to BDOS - A, B, H, L.
func setResult(cpm *CPM, res uint8) {
// H = 0
// B = 0
// L = A = res
cpm.CPU.States.AF.Hi = res
cpm.CPU.States.HL.Lo = res
cpm.CPU.States.HL.Hi = 0x00
cpm.CPU.States.BC.Hi = 0x00
if res == 0 {
cpm.CPU.States.SetFlag(z80.FlagZ)
} else {
cpm.CPU.States.ResetFlag(z80.FlagZ)
}
}
// BdosSysCallExit implements the Exit syscall
func BdosSysCallExit(cpm *CPM) error {
cpm.CPU.HALT = true
return ErrBoot
}
// BdosSysCallReadChar reads a single character from the console.
func BdosSysCallReadChar(cpm *CPM) error {
// Block for input
c, err := cpm.input.BlockForCharacterWithEcho()
if err != nil {
return fmt.Errorf("error in call to BlockForCharacter: %s", err)
}
setResult(cpm, c)
return nil
}
// BdosSysCallWriteChar writes the single character in the E register to STDOUT.
func BdosSysCallWriteChar(cpm *CPM) error {
cpm.output.PutCharacter(cpm.CPU.States.DE.Lo)
setResult(cpm, 0x00)
return nil
}
// BdosSysCallAuxRead reads a single character from the auxiliary input.
//
// Note: Echo is not enabled in this function.
func BdosSysCallAuxRead(cpm *CPM) error {
// Block for input
c, err := cpm.input.BlockForCharacterNoEcho()
if err != nil {
return fmt.Errorf("error in call to BlockForCharacterNoEcho: %s", err)
}
setResult(cpm, c)
return nil
}
// BdosSysCallAuxWrite writes the single character in the C register
// auxiliary / punch output.
func BdosSysCallAuxWrite(cpm *CPM) error {
// The character we're going to write
c := cpm.CPU.States.BC.Lo
cpm.output.PutCharacter(c)
setResult(cpm, 0x00)
return nil
}
// BdosSysCallPrinterWrite should send a single character to the printer,
// we fake that by writing to a file instead.
func BdosSysCallPrinterWrite(cpm *CPM) error {
// write the character to our printer-file
err := cpm.prnC(cpm.CPU.States.DE.Lo)
setResult(cpm, 0x00)
return err
}
// BdosSysCallRawIO handles both simple character output, and input.
//
// Note that we have to poll and determine if character input is present
// in this function, otherwise games and things don't work well without it.
//
// Blocking in the handler for 0xFF will make ZORK X work, but not other things
// this is the single hardest function to work with. Meh.
func BdosSysCallRawIO(cpm *CPM) error {
setResult(cpm, 0x0000)
switch cpm.CPU.States.DE.Lo {
case 0xFF:
// Return a character without echoing if one is waiting; zero if none is available.
if cpm.input.PendingInput() {
out, err := cpm.input.BlockForCharacterNoEcho()
if err != nil {
return err
}
setResult(cpm, out)
}
return nil
case 0xFE:
// Return console input status. Zero if no character is waiting, nonzero otherwise.
if cpm.input.PendingInput() {
setResult(cpm, 0xFF)
}
return nil
case 0xFD:
// Wait until a character is ready, return it without echoing.
out, err := cpm.input.BlockForCharacterNoEcho()
if err != nil {
return err
}
setResult(cpm, out)
return nil
default:
// Anything else is to output a character.
cpm.output.PutCharacter(cpm.CPU.States.DE.Lo)
}
return nil
}
// BdosSysCallGetIOByte gets the IOByte, which is used to describe which devices
// are used for I/O. No CP/M utilities use it, except for STAT and PIP.
//
// The IOByte lives at 0x0003 in RAM, so it is often accessed directly when it is used.
func BdosSysCallGetIOByte(cpm *CPM) error {
c := cpm.Memory.Get(0x0003)
setResult(cpm, c)
return nil
}
// BdosSysCallSetIOByte sets the IOByte, which is used to describe which devices
// are used for I/O. No CP/M utilities use it, except for STAT and PIP.
//
// The IOByte lives at 0x0003 in RAM, so it is often accessed directly when it is used.
func BdosSysCallSetIOByte(cpm *CPM) error {
// Set the value
cpm.Memory.Set(0x003, cpm.CPU.States.DE.Lo)
setResult(cpm, 0x00)
return nil
}
// BdosSysCallWriteString writes the $-terminated string pointed to by DE to STDOUT
func BdosSysCallWriteString(cpm *CPM) error {
addr := cpm.CPU.States.DE.U16()
str := ""
c := cpm.Memory.Get(addr)
for c != '$' {
// save the string we write
str += string(c)
cpm.output.PutCharacter(c)
addr++
c = cpm.Memory.Get(addr)
}
// Log the message we wrote, and its length.
cpm.log = slog.With(
slog.String("output", str),
slog.String("length", fmt.Sprintf("%d", len(str))))
setResult(cpm, 0x00)
return nil
}
// BdosSysCallReadString reads a string from the console, into the buffer pointed to by DE.
func BdosSysCallReadString(cpm *CPM) error {
// DE points to the buffer
addr := cpm.CPU.States.DE.U16()
// If DE is 0x0000 then the DMA area is used instead.
if addr == 0 {
addr = cpm.dma
}
// First byte is the max len
max := cpm.Memory.Get(addr)
// read the input
text, err := cpm.input.ReadLine(max)
if err != nil {
// Ctrl-C pressed during input.
if err == consolein.ErrInterrupted {
// Reboot the system
return ErrBoot
}
// We used the command-execution method
// and this resulted in output to send to
// the console/user.
if err == consolein.ErrShowOutput {
cpm.output.WriteString(text)
// Now we're going to re-run.
return BdosSysCallReadString(cpm)
}
return err
}
// Log the input the console received, and its length.
cpm.log = slog.With(
slog.String("input", text),
slog.String("length", fmt.Sprintf("%d", len(text))))
// addr[0] is the size of the input buffer
// addr[1] should be the size of input read, set it:
cpm.Memory.Set(addr+1, uint8(len(text)))
// addr[2+] should be the text
i := 0
for i < len(text) {
cpm.Memory.Set(uint16(addr+2+uint16(i)), text[i])
i++
}
setResult(cpm, 0x00)
return nil
}
// BdosSysCallConsoleStatus tests if we have pending console (character) input.
func BdosSysCallConsoleStatus(cpm *CPM) error {
if cpm.input.PendingInput() {
setResult(cpm, 0xFF)
return nil
}
// nothing pending.
setResult(cpm, 0x00)
return nil
}
// BdosSysCallBDOSVersion returns version details
func BdosSysCallBDOSVersion(cpm *CPM) error {
// HL = 0x0022 -CP/M 2.2
cpm.CPU.States.HL.SetU16(0x0022)
cpm.CPU.States.AF.Hi = 0x22
return nil
}
// BdosSysCallDriveAllReset resets the drives.
//
// If there is a file named "$..." then we need to return 0xFF in A,
// which will be read by the CCP - as created by SUBMIT.COM
func BdosSysCallDriveAllReset(cpm *CPM) error {
// Reset disk - but leave the user-number alone
cpm.currentDrive = 0
// Update RAM
cpm.Memory.Set(0x0004, (cpm.userNumber<<4 | cpm.currentDrive))
// Default return value
var ret uint8 = 0x00
// drive will default to our current drive, if the FCB drive field is 0
drive := string(cpm.currentDrive + 'A')
// Remap to the place we're supposed to use.
path := cpm.drives[drive]
// Look for a file with $ in its name
files, err := os.ReadDir(path)
if err == nil {
for _, n := range files {
if ret == 0x0000 && strings.Contains(n.Name(), "$") {
ret = 0xFF
}
}
}
// Reset our DMA address to the default
cpm.dma = 0x80
// Return values:
setResult(cpm, ret)
return nil
}
// BdosSysCallDriveSet updates the current drive number.
func BdosSysCallDriveSet(cpm *CPM) error {
// The drive number passed to this routine is 0 for A:, 1 for B:
// up to 15 for P:.
drv := cpm.CPU.States.AF.Hi
// P: is the maximum
if drv > 15 {
drv = 15
}
// set the drive
cpm.currentDrive = drv
// Update RAM
cpm.Memory.Set(0x0004, (cpm.userNumber<<4 | cpm.currentDrive))
setResult(cpm, 0x00)
return nil
}
// BdosSysCallFileOpen opens the filename that matches the pattern on the FCB supplied in DE
func BdosSysCallFileOpen(cpm *CPM) error {
// The pointer to the FCB
ptr := cpm.CPU.States.DE.U16()
// Get the bytes which make up the FCB entry.
xxx := cpm.Memory.GetRange(ptr, fcb.SIZE)
// Create a structure with the contents
fcbPtr := fcb.FromBytes(xxx)
// Log the FCB
cpm.log = cpm.log.With(
slog.Group("fcb_in",
slog.String("drive", fmt.Sprintf("%02X", fcbPtr.Drive)),
slog.String("name", fcbPtr.GetName()),
slog.String("type", fcbPtr.GetType()),
slog.String("seq", fmt.Sprintf("%d", fcbPtr.GetSequentialOffset())),
slog.String("rand", fmt.Sprintf("%d", fcbPtr.GetRandomOffset()*128)),
slog.String("Ex", fmt.Sprintf("%02X", fcbPtr.Ex)),
slog.String("S1", fmt.Sprintf("%02X", fcbPtr.S1)),
slog.String("S2", fmt.Sprintf("%02X", fcbPtr.S2)),
slog.String("RC", fmt.Sprintf("%02X", fcbPtr.RC)),
slog.String("CR", fmt.Sprintf("%02X", fcbPtr.Cr)),
slog.String("R0", fmt.Sprintf("%02X", fcbPtr.R0)),
slog.String("R1", fmt.Sprintf("%02X", fcbPtr.R1)),
slog.String("R2", fmt.Sprintf("%02X", fcbPtr.R2))))
// Reset the offset
fcbPtr.Ex = 0
fcbPtr.S1 = 0
fcbPtr.S2 = 0
fcbPtr.RC = 0
fcbPtr.Cr = 0
// Get the actual name
fileName := fcbPtr.GetFileName()
// No filename? That's an error
if fileName == "" {
setResult(cpm, 0xFF)
cpm.log = cpm.log.With(slog.Group("error", slog.String("message", "FileOpen with empty filename")))
return nil
}
// drive will default to our current drive, if the FCB drive field is 0
drive := cpm.currentDrive + 'A'
if fcbPtr.Drive != 0 {
drive = fcbPtr.Drive + 'A' - 1
}
// Remap to the place we're supposed to use.
path := cpm.drives[string(drive)]
//
// Ok we have a filename, but we probably have an upper-case
// filename.
//
// Run a glob, and if there's an existing file with the same
// name then replace with the mixed/lower cased version.
//
files, err2 := os.ReadDir(path)
if err2 == nil {
for _, n := range files {
if strings.ToUpper(n.Name()) == fileName {
fileName = n.Name()
}
}
}
// Ensure the filename is qualified
fileName = filepath.Join(path, fileName)
// Remapped file
x := filepath.Base(fileName)
x = filepath.Join(string(cpm.currentDrive+'A'), x)
// Can we open this file from our embedded filesystem?
virt, er := cpm.static.ReadFile(x)
if er == nil {
// Yes we can!
// Save the file handle in our cache.
cpm.files[fcbPtr.GetCacheKey()] = FileCache{name: fileName, handle: nil}
// Get file size, in blocks
fLen := uint8(len(virt) / blkSize)
// Set record-count
fcbPtr.RC = maxRC
if fLen < maxRC {
fcbPtr.RC = fLen
}
// Update the FCB in memory.
cpm.Memory.SetRange(ptr, fcbPtr.AsBytes()...)
// Return success
setResult(cpm, 0x00)
return nil
}
// Now we open from the filesystem
file, err := os.OpenFile(fileName, os.O_CREATE|os.O_RDWR, 0644)
if err != nil {
cpm.log = cpm.log.With(slog.Group("error", slog.String("message", err.Error())))
setResult(cpm, 0xFF)
return nil
}
// Save the file handle in our cache.
cpm.files[fcbPtr.GetCacheKey()] = FileCache{name: fileName, handle: file}
// Get file size, in bytes
fi, err := file.Stat()
if err != nil {
cpm.log = cpm.log.With(slog.Group("error", slog.String("message", err.Error())))
setResult(cpm, 0xFF)
return nil
}
// Get file size, in bytes
fileSize := fi.Size()
// Get file size, in blocks
fLen := uint8(fileSize / blkSize)
// Set record-count
fcbPtr.RC = maxRC
if fLen < maxRC {
fcbPtr.RC = fLen
}
// If the size is bigger than a multiple we deal with that.
if fileSize > int64(int64(fLen)*int64(blkSize)) {
fcbPtr.RC++
}
// Update the FCB in memory.
cpm.Memory.SetRange(ptr, fcbPtr.AsBytes()...)
cpm.log = cpm.log.With(
slog.Group("fcb_out",
slog.String("drive", fmt.Sprintf("%02X", fcbPtr.Drive)),
slog.String("name", fcbPtr.GetName()),
slog.String("type", fcbPtr.GetType()),
slog.String("seq", fmt.Sprintf("%d", fcbPtr.GetSequentialOffset())),
slog.String("rand", fmt.Sprintf("%d", fcbPtr.GetRandomOffset()*128)),
slog.String("Ex", fmt.Sprintf("%02X", fcbPtr.Ex)),
slog.String("S1", fmt.Sprintf("%02X", fcbPtr.S1)),
slog.String("S2", fmt.Sprintf("%02X", fcbPtr.S2)),
slog.String("RC", fmt.Sprintf("%02X", fcbPtr.RC)),
slog.String("CR", fmt.Sprintf("%02X", fcbPtr.Cr)),
slog.String("R0", fmt.Sprintf("%02X", fcbPtr.R0)),
slog.String("R1", fmt.Sprintf("%02X", fcbPtr.R1)),
slog.String("R2", fmt.Sprintf("%02X", fcbPtr.R2))))
setResult(cpm, 0x00)
return nil
}
// BdosSysCallFileClose closes the filename that matches the pattern on the FCB supplied in DE.
//
// To handle SUBMIT we need to also do more than close an existing file handle, and remove
// it from our cache. It seems that we can also be required to _truncate_ a file. Because
// I'm unsure exactly how much this is in-use I'm going to only implement it for
// files with "$" in their name.
func BdosSysCallFileClose(cpm *CPM) error {
// The pointer to the FCB
ptr := cpm.CPU.States.DE.U16()
// Get the bytes which make up the FCB entry.
xxx := cpm.Memory.GetRange(ptr, fcb.SIZE)
// Create a structure with the contents
fcbPtr := fcb.FromBytes(xxx)
// Log the FCB
cpm.log = cpm.log.With(
slog.Group("fcb_in",
slog.String("drive", fmt.Sprintf("%02X", fcbPtr.Drive)),
slog.String("name", fcbPtr.GetName()),
slog.String("type", fcbPtr.GetType()),
slog.String("seq", fmt.Sprintf("%d", fcbPtr.GetSequentialOffset())),
slog.String("rand", fmt.Sprintf("%d", fcbPtr.GetRandomOffset()*128)),
slog.String("Ex", fmt.Sprintf("%02X", fcbPtr.Ex)),
slog.String("S1", fmt.Sprintf("%02X", fcbPtr.S1)),
slog.String("S2", fmt.Sprintf("%02X", fcbPtr.S2)),
slog.String("RC", fmt.Sprintf("%02X", fcbPtr.RC)),
slog.String("CR", fmt.Sprintf("%02X", fcbPtr.Cr)),
slog.String("R0", fmt.Sprintf("%02X", fcbPtr.R0)),
slog.String("R1", fmt.Sprintf("%02X", fcbPtr.R1)),
slog.String("R2", fmt.Sprintf("%02X", fcbPtr.R2))))
// Get the file handle from our cache.
obj, ok := cpm.files[fcbPtr.GetCacheKey()]
if !ok {
setResult(cpm, 0xFF)
return nil
}
// delete the entry from the cache - regardless
// of success/failure.
delete(cpm.files, fcbPtr.GetCacheKey())
// Close of a virtual file.
if obj.handle == nil {
// Record success
setResult(cpm, 0x00)
return nil
}
// Is this a file created by submit?
if strings.HasSuffix(obj.name, "$$$.SUB") {
// Get the file size, in records
hostSize, _ := obj.handle.Seek(0, 2)
hostExtent := int((hostSize) / 16384)
seqEXT := int(fcbPtr.Ex)*32 + int(0x3F&fcbPtr.S2)
seqCR := func(n int64) int {
return int(((n) % 16384) / 128)
}
if hostExtent == seqEXT {
if int(fcbPtr.RC) < seqCR(hostSize) {
hostSize = int64(16384*seqEXT + int(128*int(fcbPtr.RC)))
err := obj.handle.Truncate(hostSize)
if err != nil {
setResult(cpm, 0xFF)
cpm.log = cpm.log.With(slog.Group("error", slog.String("message", err.Error())))
return nil
}
// We truncated
cpm.log = cpm.log.With(
slog.Group("truncated",
slog.String("hostSize", fmt.Sprintf("%d", hostSize)),
slog.String("fcbSize", fmt.Sprintf("%d", fcbPtr.RC))))
}
}
}
// close the handle
err := obj.handle.Close()
if err != nil {
setResult(cpm, 0xFF)
cpm.log = cpm.log.With(slog.Group("error", slog.String("message", err.Error())))
return nil
}
// Record success
setResult(cpm, 0x00)
return nil
}
// BdosSysCallFindFirst finds the first filename, on disk, that matches the glob in the FCB supplied in DE.
func BdosSysCallFindFirst(cpm *CPM) error {
// The pointer to the FCB
ptr := cpm.CPU.States.DE.U16()
// Get the bytes which make up the FCB entry.
xxx := cpm.Memory.GetRange(ptr, fcb.SIZE)
// Previous results are now invalidated
cpm.findFirstResults = []fcb.Find{}
// Create a structure with the contents
fcbPtr := fcb.FromBytes(xxx)
// Log the FCB
cpm.log = cpm.log.With(
slog.Group("fcb",
slog.String("drive", fmt.Sprintf("%02X", fcbPtr.Drive)),
slog.String("name", fcbPtr.GetName()),
slog.String("type", fcbPtr.GetType()),
slog.String("seq", fmt.Sprintf("%d", fcbPtr.GetSequentialOffset())),
slog.String("rand", fmt.Sprintf("%d", fcbPtr.GetRandomOffset()*128)),
slog.String("Ex", fmt.Sprintf("%02X", fcbPtr.Ex)),
slog.String("S1", fmt.Sprintf("%02X", fcbPtr.S1)),
slog.String("S2", fmt.Sprintf("%02X", fcbPtr.S2)),
slog.String("RC", fmt.Sprintf("%02X", fcbPtr.RC)),
slog.String("CR", fmt.Sprintf("%02X", fcbPtr.Cr)),
slog.String("R0", fmt.Sprintf("%02X", fcbPtr.R0)),
slog.String("R1", fmt.Sprintf("%02X", fcbPtr.R1)),
slog.String("R2", fmt.Sprintf("%02X", fcbPtr.R2))))
// Look in the correct location.
dir := cpm.drives[string(cpm.currentDrive+'A')]
// Find files in the FCB.
res, err := fcbPtr.GetMatches(dir)
if err != nil {
setResult(cpm, 0xFF)
return nil
}
// Add on any virtual files, by merging the drive.
_ = fs.WalkDir(cpm.static, string(cpm.currentDrive+'A'),
func(path string, d fs.DirEntry, err error) error {
if err != nil {
return nil
}
if d.IsDir() {
return nil
}
// Does the entry match the glob?
if fcbPtr.DoesMatch(filepath.Base(path)) {
// If so append
res = append(res, fcb.Find{
Host: path,
Name: filepath.Base(path)})
}
return nil
})
// No matches? Return an error
if len(res) < 1 {
setResult(cpm, 0xFF)
return nil
}
// Sort the list, since we've added the embedded files
// onto the end and that will look weird.
sort.Slice(res, func(i, j int) bool {
return res[i].Name < res[j].Name
})
cpm.log = cpm.log.With(
slog.Group("glob",
slog.String("pattern", fcbPtr.GetFileName()),
slog.Int("matches", len(res))))
// Build up all the results so we can log those.
tmpn := []any{}
for i, e := range res {
tmpn = append(tmpn, slog.String(fmt.Sprintf("match_%d", i), e.Name))
}
// Now make those available for logging.
cpm.log = cpm.log.With(
slog.Group("matches", tmpn...))
// Here we save the results in our cache,
// dropping the first
cpm.findFirstResults = res[1:]
// Create a new FCB and store it in the DMA entry
x := fcb.FromString(res[0].Name)
// Get file size, in blocks.
x.RC = uint8(res[0].Size / blkSize)
// If the size is bigger than a multiple we deal with that.
if res[0].Size > int64(int64(x.RC)*int64(blkSize)) {
x.RC++
}
// Log the first result we're returning.
cpm.log = cpm.log.With(
slog.Group("returning",
slog.String("name", x.GetFileName()),
slog.String("RecordCount", fmt.Sprintf("%d", x.RC))))
// Update the results
data := x.AsBytes()
cpm.Memory.SetRange(cpm.dma, data...)
// Return 0x00 to point to the first entry in the DMA area.
setResult(cpm, 0x00)
return nil
}
// BdosSysCallFindNext finds the next filename that matches the glob set in the FCB in DE.
func BdosSysCallFindNext(cpm *CPM) error {
//
// Assume we've been called with findFirst before
//
if len(cpm.findFirstResults) == 0 {
// Return 0xFF to signal an error
setResult(cpm, 0xFF)
return nil
}
// Get the first item from the list of pending files
res := cpm.findFirstResults[0]
// And update our list to remove it.
cpm.findFirstResults = cpm.findFirstResults[1:]
// Create a new FCB and store it in the DMA entry
x := fcb.FromString(res.Name)
// Get file size, in blocks.
x.RC = uint8(res.Size / blkSize)
// If the size is bigger than a multiple we deal with that.
if res.Size > int64(int64(x.RC)*int64(blkSize)) {
x.RC++
}
// Log that we're returning the next result.
cpm.log = cpm.log.With(
slog.Group("returning",
slog.String("name", x.GetFileName()),
slog.String("RecordCount", fmt.Sprintf("%d", x.RC))))
data := x.AsBytes()
cpm.Memory.SetRange(cpm.dma, data...)
// Return 0x00 to point to the first entry in the DMA area.
setResult(cpm, 0x00)
return nil
}
// BdosSysCallDeleteFile deletes the filename(s) matching the pattern specified by the FCB in DE.
func BdosSysCallDeleteFile(cpm *CPM) error {
// The pointer to the FCB
ptr := cpm.CPU.States.DE.U16()
// Get the bytes which make up the FCB entry.
xxx := cpm.Memory.GetRange(ptr, fcb.SIZE)
// Create a structure with the contents
fcbPtr := fcb.FromBytes(xxx)
// Log the FCB
cpm.log = cpm.log.With(
slog.Group("fcb",
slog.String("drive", fmt.Sprintf("%02X", fcbPtr.Drive)),
slog.String("name", fcbPtr.GetName()),
slog.String("type", fcbPtr.GetType()),
slog.String("seq", fmt.Sprintf("%d", fcbPtr.GetSequentialOffset())),
slog.String("rand", fmt.Sprintf("%d", fcbPtr.GetRandomOffset()*128)),
slog.String("Ex", fmt.Sprintf("%02X", fcbPtr.Ex)),
slog.String("S1", fmt.Sprintf("%02X", fcbPtr.S1)),
slog.String("S2", fmt.Sprintf("%02X", fcbPtr.S2)),
slog.String("RC", fmt.Sprintf("%02X", fcbPtr.RC)),
slog.String("CR", fmt.Sprintf("%02X", fcbPtr.Cr)),
slog.String("R0", fmt.Sprintf("%02X", fcbPtr.R0)),
slog.String("R1", fmt.Sprintf("%02X", fcbPtr.R1)),
slog.String("R2", fmt.Sprintf("%02X", fcbPtr.R2))))
// drive will default to our current drive, if the FCB drive field is 0
drive := cpm.currentDrive + 'A'
if fcbPtr.Drive != 0 {
drive = fcbPtr.Drive + 'A' - 1
}
// Remap to the place we're supposed to use.
path := cpm.drives[string(drive)]
// Find files that match the FCB-pattern.
res, err := fcbPtr.GetMatches(path)
if err != nil {
setResult(cpm, 0xFF)
return nil
}
// For each result, if any
for _, entry := range res {
// Host path
path := entry.Host
// Ensure we don't have this cached
x := fcb.FromString(entry.Name)
// If we have a cached handle ensure we close the file,
// then delete the entry.
obj, ok := cpm.files[x.GetCacheKey()]
if ok {
obj.handle.Close()
delete(cpm.files, x.GetCacheKey())
}
err = os.Remove(path)
if err != nil {
setResult(cpm, 0xFF)
return nil
}
}
// Build up all the results so we can log those.
tmpn := []any{}
for i, e := range res {
tmpn = append(tmpn, slog.String(fmt.Sprintf("match_%d", i), e.Name))
}
// Now make those available for logging.
cpm.log = cpm.log.With(
slog.Group("deleted", tmpn...))
setResult(cpm, 0x00)
return err
}
// BdosSysCallRead reads a record from the file named in the FCB given in DE
func BdosSysCallRead(cpm *CPM) error {
// The pointer to the FCB
ptr := cpm.CPU.States.DE.U16()
// Get the bytes which make up the FCB entry.
xxx := cpm.Memory.GetRange(ptr, fcb.SIZE)
// Create a structure with the contents
fcbPtr := fcb.FromBytes(xxx)
// Log the FCB
cpm.log = cpm.log.With(
slog.Group("fcb_in",
slog.String("drive", fmt.Sprintf("%02X", fcbPtr.Drive)),
slog.String("name", fcbPtr.GetName()),
slog.String("type", fcbPtr.GetType()),
slog.String("seq", fmt.Sprintf("%d", fcbPtr.GetSequentialOffset())),
slog.String("rand", fmt.Sprintf("%d", fcbPtr.GetRandomOffset()*128)),
slog.String("Ex", fmt.Sprintf("%02X", fcbPtr.Ex)),
slog.String("S1", fmt.Sprintf("%02X", fcbPtr.S1)),
slog.String("S2", fmt.Sprintf("%02X", fcbPtr.S2)),
slog.String("RC", fmt.Sprintf("%02X", fcbPtr.RC)),
slog.String("CR", fmt.Sprintf("%02X", fcbPtr.Cr)),
slog.String("R0", fmt.Sprintf("%02X", fcbPtr.R0)),
slog.String("R1", fmt.Sprintf("%02X", fcbPtr.R1)),
slog.String("R2", fmt.Sprintf("%02X", fcbPtr.R2))))
// Get the file handle in our cache.
obj, ok := cpm.files[fcbPtr.GetCacheKey()]
if !ok {
setResult(cpm, 0xFF)
return nil
}
// Temporary area to read into
data := make([]byte, blkSize)
// Fill the area with data
for i := range data {
data[i] = 0x1A
}
// Get the next read position
offset := fcbPtr.GetSequentialOffset()
// Are we reading from a virtual file?
if obj.handle == nil {
// Remap
p := filepath.Join(string(cpm.currentDrive+'A'), filepath.Base(obj.name))
// open
file, err := fs.ReadFile(cpm.static, p)
if err != nil {
setResult(cpm, 0xFF)
return nil
}
i := 0
// Assume success
setResult(cpm, 0x00)
// copy each appropriate byte into the data-area
for i < blkSize {
if int(offset)+i < len(file) {
data[i] = file[int(offset)+i]
} else {
setResult(cpm, 0x01)
break
}
i++
}
// Copy the data to the DMA area
cpm.Memory.SetRange(cpm.dma, data...)
// Update the next read position
fcbPtr.SetSequentialOffset(offset + 128)
// Update the FCB in memory
cpm.Memory.SetRange(ptr, fcbPtr.AsBytes()...)
// All done
return nil
}
// length of the file
fi, err3 := obj.handle.Stat()
if err3 != nil {
setResult(cpm, 0xFF)
cpm.log = cpm.log.With(slog.Group("error", slog.String("message", err3.Error())))
return nil
}
fileSize := fi.Size()
// If the offset we're reading from is bigger than the file size then
// we have to return a failure.
if offset >= fileSize {
setResult(cpm, 0x01)
return nil
}
_, err := obj.handle.Seek(int64(offset), io.SeekStart)
if err != nil {
setResult(cpm, 0xFF)
cpm.log = cpm.log.With(slog.Group("error", slog.String("message", err.Error())))
return nil
}