-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.cc
More file actions
1687 lines (1523 loc) · 53.1 KB
/
main.cc
File metadata and controls
1687 lines (1523 loc) · 53.1 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
/* An MSX-disk image creation/extraction program
Copyright (C) 2004 David Heremans <dhran@pi.be>
Copyright (C) 2005 BouKiCHi
This program is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2, or (at your option) any later
version.
As a side note: Please inform me about your modifications if you make any.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include "StringOp.hh"
#include "endian.hh"
#include <algorithm>
#include <climits>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <deque>
#include <dirent.h>
#include <getopt.h>
#include <iomanip>
#include <iostream>
#include <optional>
#include <span>
#include <sstream>
#include <string>
#include <string_view>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <utime.h>
#include <vector>
#define PRT_DEBUG(mes) \
if (showDebug) { \
std::cerr << "DEBUG: " << mes << '\n'; \
}
#define PRT_VERBOSE(mes) \
if (verboseOption) { \
std::cout << mes << '\n'; \
}
#define CRITICAL_ERROR(mes) \
std::cout << "FATAL ERROR: " << mes << '\n'; \
exit(1);
struct MSXBootSector {
uint8_t jumpCode[3]; // 0xE5 to boot program
uint8_t name[8];
Endian::UA_L16 bpSector; // uint8_ts per sector (always 512)
uint8_t spCluster; // sectors per cluster (always 2)
Endian::UA_L16 resvSectors; // amount of non-data sectors (ex boot sector)
uint8_t nrFats; // number of fats
Endian::UA_L16 dirEntries; // max number of files in root directory
Endian::UA_L16 nrSectors; // number of sectors on this disk
uint8_t descriptor; // media descriptor
Endian::UA_L16 sectorsFat; // sectors per FAT
Endian::UA_L16 sectorsTrack; // sectors per track
Endian::UA_L16 nrSides; // number of sides
Endian::UA_L16 hiddenSectors; // not used
uint8_t bootProgram[512 - 30]; // actual boot program
};
struct MSXDirEntry {
uint8_t filename[8];
uint8_t ext[3];
uint8_t attrib;
uint8_t reserved[10]; // unused
Endian::UA_L16 time;
Endian::UA_L16 date;
Endian::UA_L16 startCluster;
Endian::UA_L32 size;
};
// Modified struct taken over from Linux' fdisk.h
struct Partition {
uint8_t boot_ind; // 0x80 - active
uint8_t head; // starting head
uint8_t sector; // starting sector
uint8_t cyl; // starting cylinder
uint8_t sys_ind; // What partition type
uint8_t end_head; // end head
uint8_t end_sector; // end sector
uint8_t end_cyl; // end cylinder
Endian::UA_L32 start4; // starting sector counting from 0
Endian::UA_L32 size4; // nr of sectors in partition
};
struct PC98Part {
uint8_t bootA;
uint8_t bootB;
uint8_t reserveA[6];
uint8_t reserveB[2];
uint8_t startCyl[2];
uint8_t reserveC[2];
uint8_t endCyl[2];
uint8_t name[16];
};
static constexpr uint16_t EOF_FAT = 0x0FFF; // signals EOF in FAT12
static constexpr int SECTOR_SIZE = 512;
static constexpr int NUM_OF_ENT = SECTOR_SIZE / 0x20; // number of entries per sector
static constexpr uint8_t T_MSX_REG = 0x00; // Normal file
static constexpr uint8_t T_MSX_READ = 0x01; // Read-Only file
static constexpr uint8_t T_MSX_HID = 0x02; // Hidden file
static constexpr uint8_t T_MSX_SYS = 0x04; // System file
static constexpr uint8_t T_MSX_VOL = 0x08; // filename is Volume Label
static constexpr uint8_t T_MSX_DIR = 0x10; // entry is a subdir
static constexpr uint8_t T_MSX_ARC = 0x20; // Archive bit
struct PhysDirEntry {
int sector;
uint8_t index;
};
// The (global) disk image
std::vector<uint8_t> dskImage;
uint8_t* fsImage;
// These are set by readBootSector()
int maxCluster;
int sectorsPerCluster = 2;
int rootDirStart; // first sector from the root directory
int rootDirEnd; // last sector from the root directory
int msxChrootSector;
int msxChrootStartIndex = 0;
// These are set based on parsing the command line, TODO refactor this
bool verboseOption = false;
bool doExtract = false;
bool doSubdirs = true;
bool touchOption = false;
bool msxPartOption = false;
bool showDebug = false;
// boot block created with regular nms8250 and '_format'
static constexpr uint8_t dos1BootBlock[512] = {
0xeb,0xfe,0x90,0x4e,0x4d,0x53,0x20,0x32,0x2e,0x30,0x50,0x00,0x02,0x02,0x01,0x00,
0x02,0x70,0x00,0xa0,0x05,0xf9,0x03,0x00,0x09,0x00,0x02,0x00,0x00,0x00,0xd0,0xed,
0x53,0x59,0xc0,0x32,0xd0,0xc0,0x36,0x56,0x23,0x36,0xc0,0x31,0x1f,0xf5,0x11,0xab,
0xc0,0x0e,0x0f,0xcd,0x7d,0xf3,0x3c,0xca,0x63,0xc0,0x11,0x00,0x01,0x0e,0x1a,0xcd,
0x7d,0xf3,0x21,0x01,0x00,0x22,0xb9,0xc0,0x21,0x00,0x3f,0x11,0xab,0xc0,0x0e,0x27,
0xcd,0x7d,0xf3,0xc3,0x00,0x01,0x58,0xc0,0xcd,0x00,0x00,0x79,0xe6,0xfe,0xfe,0x02,
0xc2,0x6a,0xc0,0x3a,0xd0,0xc0,0xa7,0xca,0x22,0x40,0x11,0x85,0xc0,0xcd,0x77,0xc0,
0x0e,0x07,0xcd,0x7d,0xf3,0x18,0xb4,0x1a,0xb7,0xc8,0xd5,0x5f,0x0e,0x06,0xcd,0x7d,
0xf3,0xd1,0x13,0x18,0xf2,0x42,0x6f,0x6f,0x74,0x20,0x65,0x72,0x72,0x6f,0x72,0x0d,
0x0a,0x50,0x72,0x65,0x73,0x73,0x20,0x61,0x6e,0x79,0x20,0x6b,0x65,0x79,0x20,0x66,
0x6f,0x72,0x20,0x72,0x65,0x74,0x72,0x79,0x0d,0x0a,0x00,0x00,0x4d,0x53,0x58,0x44,
0x4f,0x53,0x20,0x20,0x53,0x59,0x53,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
// boot block created with nms8250 and MSX-DOS 2.20
static constexpr uint8_t dos2BootBlock[512] = {
0xeb,0xfe,0x90,0x4e,0x4d,0x53,0x20,0x32,0x2e,0x30,0x50,0x00,0x02,0x02,0x01,0x00,
0x02,0x70,0x00,0xa0,0x05,0xf9,0x03,0x00,0x09,0x00,0x02,0x00,0x00,0x00,0x18,0x10,
0x56,0x4f,0x4c,0x5f,0x49,0x44,0x00,0x71,0x60,0x03,0x19,0x00,0x00,0x00,0x00,0x00,
0xd0,0xed,0x53,0x6a,0xc0,0x32,0x72,0xc0,0x36,0x67,0x23,0x36,0xc0,0x31,0x1f,0xf5,
0x11,0xab,0xc0,0x0e,0x0f,0xcd,0x7d,0xf3,0x3c,0x28,0x26,0x11,0x00,0x01,0x0e,0x1a,
0xcd,0x7d,0xf3,0x21,0x01,0x00,0x22,0xb9,0xc0,0x21,0x00,0x3f,0x11,0xab,0xc0,0x0e,
0x27,0xcd,0x7d,0xf3,0xc3,0x00,0x01,0x69,0xc0,0xcd,0x00,0x00,0x79,0xe6,0xfe,0xd6,
0x02,0xf6,0x00,0xca,0x22,0x40,0x11,0x85,0xc0,0x0e,0x09,0xcd,0x7d,0xf3,0x0e,0x07,
0xcd,0x7d,0xf3,0x18,0xb8,0x42,0x6f,0x6f,0x74,0x20,0x65,0x72,0x72,0x6f,0x72,0x0d,
0x0a,0x50,0x72,0x65,0x73,0x73,0x20,0x61,0x6e,0x79,0x20,0x6b,0x65,0x79,0x20,0x66,
0x6f,0x72,0x20,0x72,0x65,0x74,0x72,0x79,0x0d,0x0a,0x24,0x00,0x4d,0x53,0x58,0x44,
0x4f,0x53,0x20,0x20,0x53,0x59,0x53,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
};
uint16_t getLE16(const uint8_t* x)
{
return (x[0] << 0) + (x[1] << 8);
}
/** Transforms a cluster number towards the first sector of this cluster
* The calculation uses info read fom the boot sector
*/
int clusterToSector(int cluster)
{
return 1 + rootDirEnd + sectorsPerCluster * (cluster - 2);
}
/** Transforms a sector number towards it containing cluster
* The calculation uses info read fom the boot sector
*/
uint16_t sectorToCluster(int sector)
{
return 2 + ((sector - (1 + rootDirEnd)) / sectorsPerCluster);
}
/** Initialize global variables by reading info from the boot sector
*/
void readBootSector()
{
const auto* boot = reinterpret_cast<const MSXBootSector*>(fsImage);
int nbSectors = boot->nrSectors;
int nbFats = boot->nrFats;
int sectorsPerFat = boot->sectorsFat;
int nbRootDirSectors = boot->dirEntries / NUM_OF_ENT;
sectorsPerCluster = boot->spCluster;
rootDirStart = 1 + nbFats * sectorsPerFat;
msxChrootSector = rootDirStart;
rootDirEnd = rootDirStart + nbRootDirSectors - 1;
maxCluster = sectorToCluster(nbSectors);
PRT_DEBUG("---------- Boot sector info -----\n"
"\n"
" bytes per sector: " << boot->bpSector << "\n"
" sectors per cluster: " << int(boot->spCluster) << "\n"
" number of FAT's: " << int(boot->nrFats) << "\n"
" dirEntries in rootDir: " << boot->dirEntries << "\n"
" sectors on disk: " << boot->nrSectors << "\n"
" media descriptor: " << std::hex << int(boot->descriptor) << std::dec << "\n"
" sectors per FAT: " << boot->sectorsFat << "\n"
" sectors per track: " << boot->sectorsTrack << "\n"
" number of sides: " << boot->nrSides << "\n"
"\n"
"Calculated values\n"
"\n"
"maxCluster " << maxCluster << "\n"
"RootDirStart " << rootDirStart << "\n"
"RootDirEnd " << rootDirEnd << "\n"
"---------------------------------\n"
"\n");
}
/** Create a correct boot sector depending on the required size of the filesystem
* Will implicitly call readBootSector for global var initialising
*/
void setBootSector(uint16_t nbSectors)
{
// variables set to single sided disk by default
uint16_t nbSides = 1;
uint8_t nbFats = 2;
uint8_t nbReservedSectors = 1; // Just copied from a 32MB IDE partition
uint8_t nbSectorsPerFat = 2;
uint8_t nbSectorsPerCluster = 2;
uint8_t nbHiddenSectors = 1;
uint16_t nbDirEntry = 112;
uint8_t descriptor = 0xf8;
// now set correct info according to size of image (in sectors!)
// and using the same layout as used by Jon in IDEFDISK v 3.1
if (nbSectors >= 32733) {
nbFats = 2; // unknown yet
nbSectorsPerFat = 12; // copied from a partition from an IDE HD
nbSectorsPerCluster = 16;
nbDirEntry = 256;
nbSides = 32; // copied from a partition from an IDE HD
nbHiddenSectors = 16;
descriptor = 0xf0;
} else if (nbSectors >= 16389) {
nbSides = 2; // unknown yet
nbFats = 2; // unknown yet
nbSectorsPerFat = 3; // unknown yet
nbSectorsPerCluster = 8;
nbDirEntry = 256;
descriptor = 0xf0;
} else if (nbSectors >= 8213) {
nbSides = 2; // unknown yet
nbFats = 2; // unknown yet
nbSectorsPerFat = 3; // unknown yet
nbSectorsPerCluster = 4;
nbDirEntry = 256;
descriptor = 0xf0;
} else if (nbSectors >= 4127) {
nbSides = 2; // unknown yet
nbFats = 2; // unknown yet
nbSectorsPerFat = 3; // unknown yet
nbSectorsPerCluster = 2;
nbDirEntry = 256;
descriptor = 0xf0;
} else if (nbSectors >= 2880) {
nbSides = 2; // unknown yet
nbFats = 2; // unknown yet
nbSectorsPerFat = 3; // unknown yet
nbSectorsPerCluster = 1;
nbDirEntry = 224;
descriptor = 0xf0;
} else if (nbSectors >= 1441) {
nbSides = 2; // unknown yet
nbFats = 2; // unknown yet
nbSectorsPerFat = 3; // unknown yet
nbSectorsPerCluster = 2;
nbDirEntry = 112;
descriptor = 0xf0;
} else if (nbSectors <= 720) {
// normal single sided disk
nbSectors = 720;
} else {
// normal double sided disk
nbSectors = 1440;
nbSides = 2;
nbFats = 2;
nbSectorsPerFat = 3;
nbSectorsPerCluster = 2;
nbDirEntry = 112;
descriptor = 0xf9;
}
auto* boot = reinterpret_cast<MSXBootSector*>(fsImage);
boot->nrSectors = nbSectors;
boot->nrSides = nbSides;
boot->spCluster = nbSectorsPerCluster;
boot->nrFats = nbFats;
boot->sectorsFat = nbSectorsPerFat;
boot->dirEntries = nbDirEntry;
boot->descriptor = descriptor;
boot->resvSectors = nbReservedSectors;
boot->hiddenSectors = nbHiddenSectors;
readBootSector();
}
// Get the next cluster number from the FAT chain
uint16_t readFAT(uint16_t clNr)
{
const uint8_t* p = fsImage + SECTOR_SIZE + (clNr * 3) / 2;
return (clNr & 1) ? (p[0] >> 4) + (p[1] << 4)
: p[0] + ((p[1] & 0x0F) << 8);
}
// Write an entry to the FAT
void writeFAT(uint16_t clNr, uint16_t val)
{
uint8_t* p = fsImage + SECTOR_SIZE + (clNr * 3) / 2;
if (clNr & 1) {
p[0] = (p[0] & 0x0F) + (val << 4);
p[1] = val >> 4;
} else {
p[0] = val;
p[1] = (p[1] & 0xF0) + ((val >> 8) & 0x0F);
}
}
// Find the next cluster number marked as free in the FAT
uint16_t findFirstFreeCluster()
{
int cluster = 2;
while ((cluster <= maxCluster) && readFAT(cluster)) {
++cluster;
}
return cluster;
}
void mkdir_ex(const char* name)
{
#ifdef __WIN32__
mkdir(name);
#else
mkdir(name, 0755);
#endif
}
/** Returns the index of a free (or with deleted file) entry
* in the current dir sector
* Out: index (is max 15), if no index is found then 16 is returned
*/
uint8_t findUsableIndexInSector(int sector)
{
// find a not used (0x00) or deleted entry (0xe5)
uint8_t* p = fsImage + SECTOR_SIZE * sector;
uint8_t i = 0;
while (i < NUM_OF_ENT && p[0] != 0x00 && p[0] != 0xe5) {
++i;
p += 32;
}
return i;
}
/** Get the next sector from a file or (sub)directory
* If no next sector then 0 is returned
*/
int getNextSector(int sector)
{
// if this sector is part of the root directory...
if (sector == rootDirEnd) return 0;
if (sector < rootDirEnd) return sector + 1;
unsigned currCluster = sectorToCluster(sector);
if (currCluster == sectorToCluster(sector + 1)) {
return sector + 1;
} else {
unsigned nextCl = readFAT(currCluster);
if (nextCl == EOF_FAT) {
return 0;
} else {
return clusterToSector(nextCl);
}
}
}
/** if there are no more free entries in a subdirectory, the subdir is
* expanded with an extra cluster, This function gets the free cluster,
* clears it and updates the fat for the subdir
* returns: the first sector in the newly appended cluster, or 0 in case of error
*/
int appendClusterToSubdir(int sector)
{
uint16_t curCl = sectorToCluster(sector);
if (readFAT(curCl) != EOF_FAT) {
CRITICAL_ERROR("appendClusterToSubdir called with sector in a not EOF_FAT cluster");
}
uint16_t nextCl = findFirstFreeCluster();
if (nextCl > maxCluster) {
std::cout << "Disk full no more free clusters\n";
return 0;
}
int logicalSector = clusterToSector(nextCl);
// clear this cluster
memset(fsImage + SECTOR_SIZE * logicalSector, 0, SECTOR_SIZE * sectorsPerCluster);
writeFAT(curCl, nextCl);
writeFAT(nextCl, EOF_FAT);
return logicalSector;
}
/** Find the dir entry for 'name' in subdir starting at the given 'sector'
* with given 'index'
* returns: a pointer to a MSXDirEntry if name was found
* a nullptr if no match was found
*/
MSXDirEntry* findEntryInDir(const std::string& name, int sector, uint8_t dirEntryIndex)
{
uint8_t* p = fsImage + SECTOR_SIZE * sector + 32 * dirEntryIndex;
uint8_t i = 0;
do {
i = 0;
while (i < NUM_OF_ENT && memcmp(name.data(), p, 11) != 0) {
++i;
p += 32;
}
if (i == NUM_OF_ENT) {
sector = getNextSector(sector);
p = fsImage + SECTOR_SIZE * sector;
}
} while (i >= NUM_OF_ENT && sector);
return sector ? reinterpret_cast<MSXDirEntry*>(p) : nullptr;
}
/** This function returns the sector and dirIndex for a new directory entry
* if needed the involved subdirectory is expanded by an extra cluster
* returns: a PhysDirEntry containing sector and index
* if failed then the sector number is 0
*/
PhysDirEntry addEntryToDir(int sector)
{
// this routine adds the msxName to a directory sector, if needed (and
// possible) the directory is extened with an extra cluster
PhysDirEntry newEntry;
uint8_t newIndex = findUsableIndexInSector(sector);
if (sector <= rootDirEnd) {
// we are adding this to the root sector
while (newIndex >= NUM_OF_ENT && sector <= rootDirEnd) {
newIndex = findUsableIndexInSector(++sector);
}
newEntry.sector = sector;
newEntry.index = newIndex;
} else {
// we are adding this to a subdir
if (newIndex < NUM_OF_ENT) {
newEntry.sector = sector;
newEntry.index = newIndex;
} else {
while (newIndex >= NUM_OF_ENT && sector != 0) {
int nextSector = getNextSector(sector);
if (nextSector == 0) {
nextSector = appendClusterToSubdir(sector);
PRT_DEBUG("appendClusterToSubdir(" << sector << ") returns" << nextSector);
if (nextSector == 0) {
CRITICAL_ERROR("disk is full");
}
}
sector = nextSector;
newIndex = findUsableIndexInSector(sector);
}
newEntry.sector = sector;
newEntry.index = newIndex;
//CRITICAL_ERROR("subdir needs more than 16 entries");
}
}
return newEntry;
}
// create an MSX filename 8.3 format, if needed in vfat like abbreviation
static char toMSXChr(char a)
{
a = toupper(a);
if (a == ' ' || a == '.') {
a = '_';
}
return a;
}
/** Transform a long hostname in a 8.3 uppercase filename as used in the
* dirEntries on an MSX
*/
std::string makeSimpleMSXFileName(std::string_view fullFilename)
{
auto [dir, fullFile] = StringOp::splitOnLast(fullFilename, "/\\");
// handle special case '.' and '..' first
std::string result(8 + 3, ' ');
if (fullFile == "." || fullFile == "..") {
memcpy(result.data(), fullFile.data(), fullFile.size());
return result;
}
auto [file, ext] = StringOp::splitOnLast(fullFile, '.');
if (file.empty()) std::swap(file, ext);
StringOp::trimRight(file, ' ');
StringOp::trimRight(ext , ' ');
// put in major case and create '_' if needed
std::string fileS(file.data(), std::min<size_t>(8, file.size()));
std::string extS (ext .data(), std::min<size_t>(3, ext .size()));
transform(fileS.begin(), fileS.end(), fileS.begin(), toMSXChr);
transform(extS .begin(), extS .end(), extS .begin(), toMSXChr);
// add correct number of spaces
memcpy(result.data() + 0, fileS.data(), fileS.size());
memcpy(result.data() + 8, extS .data(), extS .size());
return result;
}
/** This function creates a new MSX subdir with given date 'd' and time 't'
* in the subdir pointed at by 'sector' in the newly
* created subdir the entries for '.' and '..' are created
* returns: the first sector of the new subdir
* 0 in case no directory could be created
*/
int addMSXSubdir(const std::string& msxName, int t, int d, int sector)
{
// returns the sector for the first cluster of this subdir
PhysDirEntry result = addEntryToDir(sector);
if (result.index >= NUM_OF_ENT) {
std::cout << "couldn't add entry" << msxName << '\n';
return 0;
}
auto* dirEntry = reinterpret_cast<MSXDirEntry*>(
fsImage + SECTOR_SIZE * result.sector + 32 * result.index);
dirEntry->attrib = T_MSX_DIR;
dirEntry->time = t;
dirEntry->date = d;
memcpy(dirEntry, makeSimpleMSXFileName(msxName).c_str(), 11);
// dirEntry->fileSize = fSize;
uint16_t curCl = 2;
curCl = findFirstFreeCluster();
PRT_DEBUG("New subdir starting at cluster " << curCl);
dirEntry->startCluster = curCl;
writeFAT(curCl, EOF_FAT);
int logicalSector = clusterToSector(curCl);
// clear this cluster
memset(fsImage + SECTOR_SIZE * logicalSector, 0, SECTOR_SIZE * sectorsPerCluster);
// now add the '.' and '..' entries!!
dirEntry = reinterpret_cast<MSXDirEntry*>(fsImage + SECTOR_SIZE * logicalSector);
memset(dirEntry, 0, sizeof(MSXDirEntry));
memset(dirEntry, ' ', 11); // all spaces
memset(dirEntry, '.', 1);
dirEntry->attrib = T_MSX_DIR;
dirEntry->time = t;
dirEntry->date = d;
dirEntry->startCluster = curCl;
++dirEntry;
memset(dirEntry, 0, sizeof(MSXDirEntry));
memset(dirEntry, ' ', 11); // all spaces
memset(dirEntry, '.', 2);
dirEntry->attrib = T_MSX_DIR;
dirEntry->time = t;
dirEntry->date = d;
int parentCluster = sectorToCluster(sector);
if (sector == rootDirStart) parentCluster = 0;
dirEntry->startCluster = parentCluster;
return logicalSector;
}
void makeFatTime(const struct tm mtim, int* dt)
{
dt[0] = (mtim.tm_sec >> 1) + (mtim.tm_min << 5) + (mtim.tm_hour << 11);
dt[1] = mtim.tm_mday + ((mtim.tm_mon + 1) << 5) + ((mtim.tm_year + 1900 - 1980) << 9);
}
/** Add an MSXsubdir with the time properties from the HOST-OS subdir
*/
int addSubDirToDSK(const std::string& hostName, const std::string& msxName, int sector)
{
// compute time/date stamps
struct stat fst;
stat(hostName.c_str(), &fst);
struct tm mtim = *localtime(&(fst.st_mtime));
int td[2];
makeFatTime(mtim, td);
return addMSXSubdir(msxName, td[0], td[1], sector);
}
/** This file alters the filecontent of a given file
* It only changes the file content (and the filesize in the msxDirEntry)
* It doesn't changes timestamps nor filename, filetype etc.
* Output: nothing useful yet
*/
void alterFileInDSK(MSXDirEntry* msxDirEntry, const std::string& hostName)
{
bool needsNew = false;
struct stat fst;
stat(hostName.c_str(), &fst);
int fSize = fst.st_size;
PRT_DEBUG("AlterFileInDSK: filesize " << fSize);
uint16_t curCl = msxDirEntry->startCluster;
// if entry first used then no cluster assigned yet
if (curCl == 0) {
curCl = findFirstFreeCluster();
msxDirEntry->startCluster = curCl;
writeFAT(curCl, EOF_FAT);
needsNew = true;
}
PRT_DEBUG("AlterFileInDSK: starting at cluster " << curCl);
int size = fSize;
int prevCl = 0;
// open file for reading
FILE* file = fopen(hostName.c_str(), "rb");
while (file && size && (curCl <= maxCluster)) {
int logicalSector = clusterToSector(curCl);
uint8_t* buf = fsImage + logicalSector * SECTOR_SIZE;
for (int j = 0; (j < sectorsPerCluster) && size; ++j) {
PRT_DEBUG("AlterFileInDSK: relative sector " << j << " in cluster " << curCl);
size_t chunkSize = std::min(size, SECTOR_SIZE);
if (fread(buf, 1, chunkSize, file) != chunkSize) {
CRITICAL_ERROR("Error while reading from " << hostName);
}
buf += SECTOR_SIZE;
size -= chunkSize;
}
if (prevCl) {
writeFAT(prevCl, curCl);
}
prevCl = curCl;
// now we check if we continue in the current cluster string or
// need to allocate extra unused blocks do {
if (needsNew) {
// need extra space for this file
writeFAT(curCl, EOF_FAT);
curCl = findFirstFreeCluster();
} else {
// follow cluster-Fat-stream
curCl = readFAT(curCl);
if (curCl == EOF_FAT) {
curCl = findFirstFreeCluster();
needsNew = true;
}
}
//} while((curCl <= maxCluster) && ReadFAT(curCl));
PRT_DEBUG("AlterFileInDSK: continuing at cluster " << curCl);
}
if (file) fclose(file);
if ((size == 0) && (curCl <= maxCluster)) {
// TODO: check what an MSX does with filesize zero and fat allocation
if (prevCl == 0) {
prevCl = curCl;
curCl = readFAT(curCl);
}
writeFAT(prevCl, EOF_FAT);
PRT_DEBUG("AlterFileInDSK: ending at cluster " << prevCl);
// cleaning rest of FAT chain if needed
while (!needsNew) {
prevCl = curCl;
if (curCl != EOF_FAT) {
curCl = readFAT(curCl);
} else {
needsNew = true;
}
PRT_DEBUG("AlterFileInDSK: cleaning cluster " << prevCl << " from FAT");
writeFAT(prevCl, 0);
}
} else {
// TODO: don't we need a EOF_FAT in this case as well ?
// find out and adjust code here
std::cout << "Fake disk image full: " << hostName << " truncated.\n";
}
// write (possibly truncated) file size
msxDirEntry->size = fSize - size;
}
/** Add file to the MSX disk in the subdir pointed to by 'sector'
* returns: nothing useful yet :-)
*/
void addFileToDSK(const std::string& fullHostName, int sector, uint8_t dirEntryIndex)
{
auto [directory, hostName] = StringOp::splitOnLast(fullHostName, "/\\");
std::string msxName = makeSimpleMSXFileName(hostName);
// first find out if the filename already exists current dir
if (findEntryInDir(msxName, sector, dirEntryIndex)) {
PRT_VERBOSE("Preserving entry " << fullHostName);
return;
}
PhysDirEntry result = addEntryToDir(sector);
if (result.index >= NUM_OF_ENT) {
std::cout << "couldn't add entry" << fullHostName << '\n';
return;
}
auto* dirEntry = reinterpret_cast<MSXDirEntry*>(
fsImage + SECTOR_SIZE * result.sector + 32 * result.index);
dirEntry->attrib = T_MSX_REG;
dirEntry->startCluster = 0;
PRT_VERBOSE(fullHostName << " \t-> \"" << msxName << '"');
memcpy(dirEntry, msxName.c_str(), 11);
// compute time/date stamps
struct stat fst;
stat(fullHostName.c_str(), &fst);
struct tm mtim = *localtime(&(fst.st_mtime));
int td[2];
makeFatTime(mtim, td);
dirEntry->time = td[0];
dirEntry->date = td[1];
alterFileInDSK(dirEntry, fullHostName);
}
int checkStat(const std::string& name)
{
struct stat fst;
stat(name.c_str(), &fst);
if (fst.st_mode & S_IFDIR) return 0; // it's a directory
return 1; // if it's a file
}
/** transfer directory and all its subdirectories to the MSX disk image
*/
void recurseDirFill(const std::string& dirName, int sector, int dirEntryIndex)
{
PRT_DEBUG("Trying to read directory " << dirName);
DIR* dir = opendir(dirName.c_str());
if (!dir) {
PRT_DEBUG("Not a FDC_DirAsDSK image");
// throw MSXException("Not a directory");
}
// read directory and fill the fake disk
struct dirent* d = readdir(dir);
while (d) {
std::string name(d->d_name);
PRT_DEBUG("reading name in dir: " << name);
std::string path = dirName + '/' + name;
if (checkStat(path)) { // true if a file
if (name.starts_with('.')) {
std::cout << name << ": ignored file which starts with a '.'\n";
} else {
addFileToDSK(path, sector, dirEntryIndex); // used here to add file into fake dsk
}
} else if (name != "." && name != "..") {
if (doSubdirs) {
std::string msxName = makeSimpleMSXFileName(name);
PRT_VERBOSE(path << " \t-> \"" << msxName << '"');
int result;
if (auto* msxDirEntry = findEntryInDir(msxName, sector, dirEntryIndex)) {
PRT_VERBOSE("Dir entry " << name << " exists already");
result = clusterToSector(msxDirEntry->startCluster);
} else {
PRT_VERBOSE("Adding dir entry " << name);
result = addSubDirToDSK(path, name, sector); // used here to add file into fake dsk
}
recurseDirFill(path, result, 0);
} else {
PRT_DEBUG("Skipping subdir: " << path);
}
}
d = readdir(dir);
}
closedir(dir);
}
/** Save the disk image from memory to disk
*/
void writeImageToDisk(const std::string& filename)
{
FILE* file = fopen(filename.c_str(), "wb");
if (!file) {
std::cout << "Couldn't open file for writing!\n";
return;
}
fwrite(dskImage.data(), 1, dskImage.size(), file);
fclose(file);
}
void updateCreateDSK(const std::string& fileName)
{
std::string msxName = makeSimpleMSXFileName(fileName);
PRT_DEBUG("trying to stat: " << fileName);
struct stat fst;
stat(fileName.c_str(), &fst);
if (fst.st_mode & S_IFDIR) {
// this should be a directory
if (!doSubdirs) {
// put files in the directory to root
recurseDirFill(fileName, msxChrootSector, msxChrootStartIndex);
} else {
PRT_VERBOSE("./" << fileName << " \t-> \"" << msxName << '"');
int result;
if (auto* msxDirEntry = findEntryInDir(msxName, msxChrootSector, msxChrootStartIndex)) {
PRT_VERBOSE("Dir entry " << fileName << " exists already");
result = clusterToSector(msxDirEntry->startCluster);
} else {
PRT_VERBOSE("Adding dir entry " << fileName);
result = addSubDirToDSK(fileName, fileName, msxChrootSector);
// used here to add file into fake dsk
}
recurseDirFill(fileName, result, 0);
}
} else {
// this should be a normal file
PRT_VERBOSE("Updating file " << fileName);
// addFileToDSK(fileName, MSXchrootSector, MSXchrootStartIndex); // used here to add file into fake dsk in root dir!!
// first find out if the filename already exists current dir
MSXDirEntry* msxDirEntry = findEntryInDir(msxName, msxChrootSector, msxChrootStartIndex);
alterFileInDSK(msxDirEntry, fileName);
}
}
void addCreateDSK(const std::string& fileName)
{
// Here we create the fake disk images based upon the files that can be
// found in the 'fileName' directory or the single file
PRT_DEBUG("addCreateDSK(" << fileName << ");");
struct stat fst;
stat(fileName.c_str(), &fst);
if (fst.st_mode & S_IFDIR) {
// this should be a directory
PRT_VERBOSE("addCreateDSK: adding directory " << fileName);
if (!doSubdirs) {
// put files in the directory to root
recurseDirFill(fileName, msxChrootSector, msxChrootStartIndex);
} else {
std::string msxName = makeSimpleMSXFileName(fileName);
PRT_VERBOSE("./" << fileName << " \t-> \"" << msxName << '"');
int result;
if (auto* msxDirEntry = findEntryInDir(msxName, msxChrootSector, msxChrootStartIndex)) {
PRT_VERBOSE("Dir entry " << fileName << " exists already ");
result = clusterToSector(msxDirEntry->startCluster);
} else {
PRT_VERBOSE("Adding dir entry " << fileName);
result = addSubDirToDSK(fileName, fileName, msxChrootSector);
// used here to add file into fake dsk
}
recurseDirFill(fileName, result, 0);
}
} else {
// this should be a normal file
PRT_VERBOSE("Adding file " << fileName);
addFileToDSK(fileName, msxChrootSector, msxChrootStartIndex); // used here to add file into fake dsk in root dir!!
}
}
void updateInDSK(std::string name, bool keep)
{
StringOp::trimRight(name, "/\\");
// first find the filename in the current 'root dir'
if (findEntryInDir(makeSimpleMSXFileName(name), rootDirStart, 0)) {
if (keep) {
PRT_VERBOSE("Preserving entry " << name);
} else {
updateCreateDSK(name);
}
} else {
PRT_VERBOSE("Couldn't find entry " << name <<
" to update, trying to create new entry");
addCreateDSK(name);
}
}
/** Create an empty disk image with correct boot sector,FAT etc.
*/
void createEmptyDSK(int nbSectors, bool dos2)
{
// First create structure for the fake disk
// Allocate dskImage in memory
dskImage.assign(nbSectors * SECTOR_SIZE, 0xE5);
fsImage = dskImage.data();
// Assign default boot disk to this instance
// give extra info on the boot sector
// and get global parameters from them (implicit readBootSector)
memcpy(fsImage, dos2 ? dos2BootBlock : dos1BootBlock, SECTOR_SIZE);
setBootSector(nbSectors);
// Assign default empty values to disk
memset(fsImage + SECTOR_SIZE, 0x00, rootDirEnd * SECTOR_SIZE);
// for some reason the first 3uint8_ts are used to indicate the end of a
// cluster, making the first available cluster nr 2 some sources say
// that this indicates the disk format and FAT[0]should 0xF7 for single
// sided disk, and 0xF9 for double sided disks
// TODO: check this :-)
// for now I simply repeat the media descriptor here
{
const auto* boot = reinterpret_cast<const MSXBootSector*>(fsImage);
fsImage[SECTOR_SIZE + 0] = boot->descriptor;
}
fsImage[SECTOR_SIZE + 1] = 0xFF;
fsImage[SECTOR_SIZE + 2] = 0xFF;
}
std::string condenseName(const MSXDirEntry* dirEntry)
{
char condensedName[8 + 1 + 3 + 1];
char* p = condensedName;
for (int i = 0; i < 8; ++i) {
if (dirEntry->filename[i] == ' ') {
i = 9;
} else {
*(p++) = tolower(dirEntry->filename[i]);
}
}
if (dirEntry->ext[0] != ' ' || dirEntry->ext[1] != ' ' || dirEntry->ext[2] != ' ') {
*(p++) = '.';
for (int i = 0; i < 3; ++i) {
*p = tolower(dirEntry->ext[i]);
if (*p == ' ') *p = char(0);
++p;
}
}
*p = char(0);
return condensedName;