-
Notifications
You must be signed in to change notification settings - Fork 0
/
dllmain.c
2185 lines (1947 loc) · 63.1 KB
/
dllmain.c
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
//TODO: "If PK_CAPS_HIDE is set, the plugin will not show the file type as a packer. This is useful for plugins which are mainly used for creating files, e.g. to create batch files, avi files etc. The file needs to be opened with Ctrl+PgDn in this case, because Enter will launch the associated application."
// ==>altho this would require a second build with different filenames etc - the "gibberish extension"-solution is clumsy, but easier \o/
#define VERSION_NO "v0.10"
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#endif
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <sys/stat.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#define DIR_SEPARATOR_STRING "\\"
#define FOPEN_S(a,b,c) fopen_s(&a,b,c)
#else
#include <unistd.h>
#define DIR_SEPARATOR_STRING "/"
#define __stdcall
#define sprintf_s(a,b,...) sprintf(a,__VA_ARGS__)
#define strcpy_s(a,b,c) strcpy(a,c)
#define FOPEN_S(a,b,c) a=fopen(b,c)
#define _strcmpi strcasecmp
typedef char *LPCSTR;
#define _stat stat
#define _ftelli64 ftello
#include <signal.h>
#define DebugBreak() raise(SIGTRAP);
#include <ctype.h>
#define TRUE true
#define FALSE false
#define BOOL bool
#include <stdbool.h>
#include <stdlib.h>
#endif
#if _MSC_VER
#define INLINE __forceinline
#elif defined(__APPLE__)
#define INLINE
#else
#define INLINE static inline
#endif
#include "wcxhead.h"
// This define needs to be before including dosfs.h
#define ATARI_ST_SPECIFIC
#include "dosfs-1.03/dosfs.h"
#include "jacknife.h"
#define STORAGE_BYTES 65536 - sizeof(void *) - sizeof(unsigned short)
typedef struct entrylist_storage_
{
struct entrylist_storage_ *prev;
unsigned short current_offset;
unsigned char data[STORAGE_BYTES];
} ENTRYLIST_STORAGE;
stEntryList entryList;
tArchive* pCurrentArchive;
typedef tArchive* myHANDLE;
DISK_IMAGE_INFO disk_image;
ENTRYLIST_STORAGE *current_storage = NULL;
tProcessDataProc ProcessDataProc;
int current_partition; // TODO: terrible, find some better way!
// The following 2 routines were lifted from https://github.com/greiman/SdFat
// tweaked a bit to suit our needs
typedef struct FatLfn
{
/** UTF-16 length of Long File Name */
//size_t len;
/** Position for sequence number. */
uint8_t seqPos;
/** Flags for base and extension character case and LFN. */
uint8_t flags;
/** Short File Name */
uint8_t sfn[11];
const char *lfn;
} FatLfn_t;
#define FAT_NAME_FREE 0X00; /** name[0] value for entry that is free and no allocated entries follow */
#define FAT_NAME_DELETED 0XE5; /** name[0] value for entry that is free after being "deleted" */
// Directory attribute of volume label.
#define FAT_ATTRIB_LABEL 0x08;
#define FAT_ATTRIB_LONG_NAME 0X0F;
#define FAT_CASE_LC_BASE 0X08; /** Filename base-name is all lower case */
#define FAT_CASE_LC_EXT 0X10; /** Filename extension is all lower case.*/
#define FNAME_FLAG_LOST_CHARS 0X01 /** Derived from a LFN with loss or conversion of characters. */
#define FNAME_FLAG_MIXED_CASE 0X02 /** Base-name or extension has mixed case. */
#define FNAME_FLAG_NEED_LFN (FNAME_FLAG_LOST_CHARS | FNAME_FLAG_MIXED_CASE) /** LFN entries are required for file name. */
#define FNAME_FLAG_LC_BASE FAT_CASE_LC_BASE /** Filename base-name is all lower case */
#define FNAME_FLAG_LC_EXT FAT_CASE_LC_EXT /** Filename extension is all lower case. */
#define DBG_HALT_IF(b) \
if (b) { \
DebugBreak() ; \
}
#define DBG_HALT_MACRO DebugBreak()
#define DBG_WARN_IF(b) \
if (b) { \
printf("%d\n", __LINE__); \
}
//------------------------------------------------------------------------------
// Reserved characters for FAT short 8.3 names.
INLINE BOOL sfnReservedChar(uint8_t c) {
if (c == '"' || c == '|' || c == '[' || c == '\\' || c == ']') {
return TRUE;
}
// *+,./ or :;<=>?
if ((0X2A <= c && c <= 0X2F && c != 0X2D) || (0X3A <= c && c <= 0X3F)) {
return TRUE;
}
// Reserved if not in range (0X20, 0X7F).
return !(0X20 < c && c < 0X7F);
}
BOOL makeSFN(FatLfn_t* fname) {
BOOL is83;
// char c;
uint8_t c;
uint8_t bit = FAT_CASE_LC_BASE;
uint8_t lc = 0;
uint8_t uc = 0;
uint8_t i = 0;
uint8_t in = 7;
const char* dot;
const char *end = fname->lfn + strlen(fname->lfn);
const char* ptr = fname->lfn;
// Assume not zero length.
//DBG_HALT_IF(end == ptr);
if (end == ptr) return FALSE;
// Assume blanks removed from start and end.
DBG_HALT_IF(*ptr == ' ' || *(end - 1) == ' ' || *(end - 1) == '.');
// Blank file short name.
for (uint8_t k = 0; k < 11; k++) {
fname->sfn[k] = ' ';
}
// Not 8.3 if starts with dot.
is83 = *ptr == '.' ? FALSE : TRUE;
// Skip leading dots.
for (; *ptr == '.'; ptr++) {
}
// Find last dot.
for (dot = end - 1; dot > ptr && *dot != '.'; dot--) {
}
for (; ptr < end; ptr++) {
c = *ptr;
if (c == '.' && ptr == dot) {
in = 10; // Max index for full 8.3 name.
i = 8; // Place for extension.
bit = FAT_CASE_LC_EXT; // bit for extension.
} else {
if (sfnReservedChar(c)) {
is83 = FALSE;
// Skip UTF-8 trailing characters.
if ((c & 0XC0) == 0X80) {
continue;
}
c = '_';
}
if (i > in) {
is83 = FALSE;
if (in == 10 || ptr > dot) {
// Done - extension longer than three characters or no extension.
break;
}
// Skip to dot.
ptr = dot - 1;
continue;
}
//if (isLower(c)) {
if (islower(c)) {
c += 'A' - 'a';
lc |= bit;
//} else if (isUpper(c)) {
} else if (isupper(c)) {
uc |= bit;
}
fname->sfn[i++] = c;
if (i < 7) {
fname->seqPos = i;
}
}
}
if (fname->sfn[0] == ' ') {
DBG_HALT_MACRO;
{
int debug_halt = 0;
}
goto fail;
}
if (is83) {
fname->flags = (lc & uc) ? FNAME_FLAG_MIXED_CASE : lc;
} else {
fname->flags = FNAME_FLAG_LOST_CHARS;
fname->sfn[fname->seqPos] = '~';
fname->sfn[fname->seqPos + 1] = '1';
}
return TRUE;
fail:
return FALSE;
}
// ggn: Unsure if we'll go so deep into this. Generally, people shouldn't use long filenames.
// For now we'll probably hammer a "~1" in the filename and hope people don't try to abuse this too much
// (another reason for punting on this for now is that we'll have to (re)scan the current directory listing
// to ensure no collision happens
//typedef struct {
// uint8_t name[11];
// uint8_t attributes;
// uint8_t caseFlags;
// uint8_t createTimeMs;
// uint8_t createTime[2];
// uint8_t createDate[2];
// uint8_t accessDate[2];
// uint8_t firstClusterHigh[2];
// uint8_t modifyTime[2];
// uint8_t modifyDate[2];
// uint8_t firstClusterLow[2];
// uint8_t fileSize[4];
//} DirFat_t;
//BOOL makeUniqueSfn(FatLfn_t* fname) {
// const uint8_t FIRST_HASH_SEQ = 2; // min value is 2
// uint8_t pos = fname->seqPos;
// DirFat_t* dir;
// uint16_t hex = 0;
//
// DBG_HALT_IF(!(fname->flags & FNAME_FLAG_LOST_CHARS));
// DBG_HALT_IF(fname->sfn[pos] != '~' && fname->sfn[pos + 1] != '1');
//
// for (uint8_t seq = FIRST_HASH_SEQ; seq < 100; seq++) {
// DBG_WARN_IF(seq > FIRST_HASH_SEQ);
// hex += millis();
// if (pos > 3) {
// // Make space in name for ~HHHH.
// pos = 3;
// }
// for (uint8_t i = pos + 4; i > pos; i--) {
// uint8_t h = hex & 0XF;
// fname->sfn[i] = h < 10 ? h + '0' : h + 'A' - 10;
// hex >>= 4;
// }
// fname->sfn[pos] = '~';
// rewind();
// while (1) {
// dir = readDirCache(TRUE);
// if (!dir) {
// if (!getError()) {
// // At EOF and name not found if no error.
// goto done;
// }
// DBG_FAIL_MACRO;
// goto fail;
// }
// if (dir->name[0] == FAT_NAME_FREE) {
// goto done;
// }
// if (isFatFileOrSubdir(dir) && !memcmp(fname->sfn, dir->name, 11)) {
// // Name found - try another.
// break;
// }
// }
// }
// // fall inti fail - too many tries.
// DBG_FAIL_MACRO;
//
// fail:
// return FALSE;
//
// done:
// return TRUE;
//}
//unpack MSA into a newly created buffer
uint8_t *unpack_msa(tArchive *arch, uint8_t *packedMsa, int packedSize)
{
int sectors = ((int)packedMsa[2] << 8) | ((int)packedMsa[3]);
int sides = (((int)packedMsa[4] << 8) | ((int)packedMsa[5])) + 1;
int startTrack = ((int)packedMsa[6] << 8) | ((int)packedMsa[7]);
int endTrack = (((int)packedMsa[8] << 8) | ((int)packedMsa[9])) + 1;
//just ignore partial disk images, skipping tracks would skip bpb/fat, too
if (startTrack != 0 || endTrack == 0) {
return NULL;
}
int unpackedSize = sectors * 512 * sides * endTrack;
disk_image.image_sectors = sectors;
disk_image.image_sides = sides;
disk_image.image_tracks = endTrack;
uint8_t *unpackedData = (uint8_t *)malloc(unpackedSize);
if (!unpackedData) return 0;
int offset = 10;
int out = 0;
for (int i = 0; i < endTrack * sides; i++) {
int trackLen = packedMsa[offset++];
trackLen <<= 8;
trackLen += packedMsa[offset++];
if (trackLen != 512 * sectors) {
for (; trackLen > 0; trackLen--) {
unpackedData[out++] = packedMsa[offset++];
// Bounds check against corrupt MSA images
if (out > unpackedSize || offset > packedSize)
{
free(unpackedData);
return 0;
}
if (unpackedData[out - 1] == 0xe5) {
// Bounds check against corrupt MSA images
if (offset + 4 - 1 > packedSize)
{
free(unpackedData);
return 0;
}
uint8_t data = packedMsa[offset++];
unsigned int runLen = packedMsa[offset++];
runLen <<= 8;
runLen += packedMsa[offset++];
trackLen -= 3;
out--;
for (unsigned int ii = 0; ii < runLen && out < unpackedSize; ii++) {
unpackedData[out++] = data;
}
}
}
}
else {
// Bounds check against corrupt MSA images
if (out + trackLen > unpackedSize || offset + trackLen > packedSize)
{
free(unpackedData);
return 0;
}
for (; trackLen > 0; trackLen--) {
unpackedData[out++] = packedMsa[offset++];
}
}
}
disk_image.file_size = unpackedSize;
return unpackedData;
}
BOOL guess_size(int size)
{
if (size % 512) {
return FALSE;
}
int tracks, sectors;
int start_sectors = 11;
// If our image is greater than 1mb, then it's a HD image. Not the best way to detect
// HD disks in general, but it should hold
if (size > 83 * 11 * 512 * 2)
{
start_sectors = 21;
}
for (tracks = 86; tracks > 0; tracks--) {
for (sectors = start_sectors; sectors >= start_sectors - 3; sectors--) {
if (!(size % tracks)) {
if ((size % (tracks * sectors * 2 * 512)) == 0) {
disk_image.image_tracks = tracks;
disk_image.image_sides = 2;
disk_image.image_sectors = sectors;
return TRUE;
}
else if ((size % (tracks * sectors * 1 * 512)) == 0) {
disk_image.image_tracks = tracks;
disk_image.image_sides = 1;
disk_image.image_sectors = sectors;
return TRUE;
}
}
}
}
return FALSE;
}
#define BYTE_SWAP_WORD(a) ((unsigned short)(a>>8)|(unsigned short)(a<<8))
BOOL dim_copy_sector_or_fill_with_blank(int fat_entry, void *s, void *d, int cluster_size, int bytes_left)
{
if (fat_entry == 0 || (fat_entry >= 0xff0 && fat_entry <= 0xff7) || bytes_left <= 0)
{
return FALSE;
}
if (bytes_left >= cluster_size)
{
memcpy(d, s, cluster_size);
}
else
{
// Yes, there are .dim files that are truncated at the end
memcpy(d, s, bytes_left);
}
return TRUE;
}
unsigned char *expand_dim(BOOL fastcopy_header)
{
unsigned char *buf = (unsigned char *)calloc(1, disk_image.image_tracks * disk_image.image_sectors * disk_image.image_sides * 512);
unsigned char *d = buf;
if (!d) return 0;
unsigned char *s = disk_image.buffer;
FCOPY_HEADER *h = (FCOPY_HEADER *)s;
s += 32;
int total_filesystem_sectors = BYTE_SWAP_WORD(h->total_filesystem_sectors);
int bytes_left = (int)(disk_image.file_size - total_filesystem_sectors * 512);
if (fastcopy_header)
bytes_left -= 32;
memcpy(d, s, total_filesystem_sectors * 512);
s += total_filesystem_sectors * 512;
d += total_filesystem_sectors * 512;
unsigned char *fat1 = disk_image.buffer + 512+32 + 3; // TODO: A bit hardcoded, but eh
int cluster_size = BYTE_SWAP_WORD(h->cluster_size);
for (int i = 0; i < BYTE_SWAP_WORD(h->total_clusters) / 2; i++)
{
BOOL ret;
// Check "even" entry in a FAT12 record
int fat_entry = ((fat1[1] & 0xf) << 8) | fat1[0];
ret = dim_copy_sector_or_fill_with_blank(fat_entry, s, d, cluster_size, bytes_left);
d += cluster_size;
if (ret)
{
s += cluster_size;
bytes_left -= cluster_size;
}
// Check "odd" entry in a FAT12 record
fat_entry = (fat1[2] << 4) | (fat1[1] >> 4);
ret = dim_copy_sector_or_fill_with_blank(fat_entry, s, d, cluster_size, bytes_left);
d += cluster_size;
if (ret)
{
s += cluster_size;
bytes_left -= cluster_size;
}
// Advance through 2 FAT12 entries
fat1 += 3;
}
return buf;
}
/*
Attach emulation to a host-side disk image file
Returns 0 OK, nonzero for any error
*/
uint32_t DFS_HostAttach(tArchive *arch)
{
disk_image.image_opened_read_only = FALSE;
disk_image.file_handle = fopen(arch->archname, "r+b");
if (disk_image.file_handle == NULL)
{
// Maybe the image is write protected, try to open read only
disk_image.file_handle = fopen(arch->archname, "rb");
if (disk_image.file_handle == NULL)
{
return J_FILE_NOT_FOUND;
}
disk_image.image_opened_read_only = TRUE;
}
fseek(disk_image.file_handle, 0, SEEK_END);
disk_image.file_size = _ftelli64(disk_image.file_handle);
fseek(disk_image.file_handle, 0, SEEK_SET);
disk_image.disk_geometry_does_not_match_bpb = FALSE;
disk_image.mode = DISKMODE_HARD_DISK;
if (disk_image.file_size > 2880 * 1024)
{
// Hard disk image, we'll do everything in-place inside the file
return J_OK;
}
// Definitely a floppy disk image, let's cache it into RAM
disk_image.buffer = (uint8_t *)malloc((size_t)disk_image.file_size);
if (!disk_image.buffer)
{
return J_MALLOC_ERROR;
}
if (!fread(disk_image.buffer, (size_t)disk_image.file_size, 1, disk_image.file_handle))
{
fclose(disk_image.file_handle);
return -1;
}
fclose(disk_image.file_handle);
// Try to figure out what kind of image we got here. We first assume it's just a sector dump (.ST)
// and then we scan for MSA and FastCopy DIM headers. If we detect either, go do some extra stuff
disk_image.mode = DISKMODE_LINEAR;
if ((disk_image.buffer[0] == 0xe && disk_image.buffer[1] == 0xf) ||
(disk_image.buffer[0] == 0x0 && disk_image.buffer[1] == 0x0 && strlen(arch->archname) > 4 && _strcmpi(arch->archname + strlen(arch->archname) - 4, ".msa") == 0))
{
// MSA image, unpack it to a flat buffer
disk_image.mode = DISKMODE_MSA;
uint8_t *unpacked_msa = unpack_msa(arch, disk_image.buffer, (int)disk_image.file_size);
free(disk_image.buffer);
if (!unpacked_msa)
{
return J_INVALID_MSA;
}
disk_image.buffer = unpacked_msa;
}
else if (*(unsigned short *)disk_image.buffer == 0x4242)
{
// Fastcopy DIM image, unpack it to flat buffer if needed
FCOPY_HEADER *h = (FCOPY_HEADER *)disk_image.buffer;
if (h->start_track)
{
// Nope, we don't support partial images
return J_INALID_DIM;
}
if (h->disk_configuration_present)
{
disk_image.image_sectors = h->sectors;
disk_image.image_sides = h->sides + 1;
disk_image.image_tracks = h->end_track + 1;
if (h->get_sectors)
{
// Disk was imaged with "Get sectors" on, so we need to
// expand the image to fill in the non-imaged sectors with blanks
disk_image.mode = DISKMODE_FCOPY_CONF_USED_SECTORS;
uint8_t *expanded = expand_dim(TRUE);
if (!expanded)
{
return J_INALID_DIM;
}
disk_image.buffer = expanded;
}
else
{
// No problem, just skip past the FCopy header and treat it as a normal .ST disk
disk_image.mode = DISKMODE_FCOPY_CONF_ALL_SECTORS;
disk_image.buffer += 32;
}
}
else
{
disk_image.mode = DISKMODE_FCOPY_NO_CONF;
disk_image.buffer += 32;
}
}
else
{
if (!guess_size((int)disk_image.file_size))
{
free(disk_image.buffer);
return -1;
}
}
return J_OK;
}
// For reasons explained in DFS_GetVolInfo, the image's geometry can be different than what
// the BPB reports. When we detect such a case we need to translate the requested sector
// from the "logical" geometry to the "physical" one. Basically we convert the sector to
// track/sector/side and then convert it back to a sector count using the detected disk geometry.
uint32_t recalculate_sector(uint32_t sector)
{
uint32_t requested_track = sector / disk_image.bpb_sectors_per_track / disk_image.bpb_sides;
uint32_t requested_side = (sector % (disk_image.bpb_sectors_per_track * disk_image.bpb_sides)) / disk_image.bpb_sectors_per_track;
uint32_t requested_sector = sector % disk_image.bpb_sectors_per_track;
return requested_track * disk_image.image_sectors * disk_image.image_sides +
requested_side * disk_image.image_sectors +
requested_sector;
}
/*
Read sector from image
Returns 0 OK, nonzero for any error
*/
int DFS_HostReadSector(uint8_t *buffer, uint32_t sector, uint32_t count)
{
if (disk_image.disk_geometry_does_not_match_bpb)
{
// Wonky disk image detected, let's recalculate the requested sector
sector = recalculate_sector(sector);
assert(count == 1); // Leave this here just to remind us that anything if count>1 it could mean Very Bad Things(tm)
}
// fseek into an opened for writing file can extend the file on Windows and won't fail, so let's check bounds
if ((int)(sector * SECTOR_SIZE) > disk_image.file_size)
{
return -1;
}
if (disk_image.mode != DISKMODE_HARD_DISK)
{
// It's cached in ram, so let's not hit the disk
memcpy(buffer, &disk_image.buffer[sector * SECTOR_SIZE], SECTOR_SIZE);
return 0;
}
else
{
// TODO: what in the world is this abomination of a test? Simplify
if (current_partition!=-1 && disk_image.partition_info[current_partition].partition_defined && (sector<disk_image.partition_info[current_partition].start_sector || sector>disk_image.partition_info[current_partition].start_sector + disk_image.partition_info[current_partition].total_sectors))
{
return -1;
}
if (fseek(disk_image.file_handle, sector * SECTOR_SIZE, SEEK_SET))
{
return -1;
}
fread(buffer, SECTOR_SIZE, count, disk_image.file_handle);
return 0;
}
}
uint32_t DFS_ReadSector(uint8_t unit, uint8_t *buffer, uint32_t sector, uint32_t count)
{
return DFS_HostReadSector(buffer, sector, count);
}
/*
Write sector to image
Returns 0 OK, nonzero for any error
*/
int DFS_HostWriteSector(uint8_t *buffer, uint32_t sector, uint32_t count)
{
if (disk_image.image_opened_read_only) return -1;
if (disk_image.disk_geometry_does_not_match_bpb)
{
// Wonky disk image detected, let's recalculate the requested sector
sector = recalculate_sector(sector);
assert(count == 1); // Leave this here just to remind us that anything if count>1 it could mean Very Bad Things(tm)
}
// fseek into an opened for writing file can extend the file on Windows and won't fail, so let's check bounds
if ((int)(sector * SECTOR_SIZE) > disk_image.file_size)
{
return -1;
}
// It's cached in ram, so let's not hit the disk
if (disk_image.mode != DISKMODE_HARD_DISK)
{
if (sector > disk_image.file_size/512)
{
return -1;
}
memcpy(&disk_image.buffer[sector * SECTOR_SIZE], buffer, SECTOR_SIZE);
return 0;
}
else
{
// TODO: what in the world is this abomination of a test? Simplify
if (current_partition != -1 && disk_image.partition_info[current_partition].partition_defined && (sector<disk_image.partition_info[current_partition].start_sector || sector>disk_image.partition_info[current_partition].start_sector + disk_image.partition_info[current_partition].total_sectors))
{
return -1;
}
if (fseek(disk_image.file_handle, sector * SECTOR_SIZE, SEEK_SET))
{
return -1;
}
fwrite(buffer, SECTOR_SIZE, count, disk_image.file_handle);
fflush(disk_image.file_handle);
return 0;
}
}
uint32_t DFS_WriteSector(uint8_t unit, uint8_t *buffer, uint32_t sector, uint32_t count)
{
return DFS_HostWriteSector(buffer, sector, count);
}
// try to pack a chunk of data in MSA RLE format
// returns packed size or -1 if packing was unsuccessful
static int pack_track(unsigned char *dest, const unsigned char *src, int len) {
int pklen = 0;
const unsigned char *p = (const unsigned char *)src, *src_end = (const unsigned char *)src + len;
while (p < src_end) {
const unsigned char *prev = p;
unsigned int pkv = *p++;
while (p < src_end && *p == pkv) p++;
int n = (int)(p - prev);
if ((n >= 4 || pkv == 0xE5) && pklen + 4 < len) {
*dest++ = 0xE5;
*dest++ = pkv;
*dest++ = n >> 8;
*dest++ = n;
pklen += 4;
}
else if (pklen + n < len) {
int i;
for (i = 0; i < n; ++i) *dest++ = pkv;
pklen += n;
}
else {
return -1;
}
}
return pklen;
}
uint8_t *make_msa(tArchive *arch)
{
// Write MSA header
int sectors = disk_image.image_sectors;
int sides = disk_image.image_sides;
int start_track = 0;
int end_track = disk_image.image_tracks - 1;
unsigned char *packed_buffer = (unsigned char *)malloc(10 + end_track * (sectors * SECTOR_SIZE + 2) * sides + 100000); // 10=header size, +2 bytes per track for writing the track size
if (!packed_buffer) return 0;
unsigned char *pack = packed_buffer;
*(unsigned short *)(pack + 0) = 0x0f0e;
*(unsigned short *)(pack + 2) = ((unsigned short)( sectors << 8)) | ((unsigned short)( sectors >> 8));
*(unsigned short *)(pack + 4) = ((unsigned short)((sides - 1) << 8)) | ((unsigned short)((sides - 1) >> 8));
*(unsigned short *)(pack + 6) = 0; // Start track will always be 0
*(unsigned short *)(pack + 8) = ((unsigned short)( end_track << 8)) | ((unsigned short)( end_track >> 8));
pack += 10;
int track;
unsigned char *p = disk_image.buffer;
for (track = 0; track < end_track + 1; ++track) {
int side;
for (side = 0; side < sides; ++side) {
// try to compress the track
int pklen = pack_track(pack + 2, p, sectors * 512);
if (pklen < 0) {
// compression failed, writing uncompressed
*(unsigned short *)(pack) = (unsigned short)((sectors * SECTOR_SIZE) >> 8) | (unsigned short)((sectors * SECTOR_SIZE) << 8);
memcpy(pack + 2, p, sectors * 512);
pack += 2 + SECTOR_SIZE * sectors;
}
else {
// write the compressed data
*(unsigned short *)(pack) = (unsigned short)(pklen >> 8) | (unsigned short)(pklen << 8);
pack += 2 + pklen;
}
p += sectors * 512;
}
}
disk_image.file_size = (int)(pack - packed_buffer);
return packed_buffer;
}
int DFS_HostDetach(tArchive *arch)
{
if (disk_image.mode == DISKMODE_HARD_DISK)
{
// Just close the file, we're done
if (!disk_image.file_handle) return -1;
return fclose(disk_image.file_handle);
}
if (disk_image.mode == DISKMODE_FCOPY_CONF_ALL_SECTORS || disk_image.mode == DISKMODE_FCOPY_NO_CONF)
{
// Rewind pointer here because we might want to free it
disk_image.buffer -= 32;
}
// Floppy image, we have some work to do
if (!arch->volume_dirty)
{
// Only try to save the image to disk if we actually modified it
// If we performed a file operation (add files, new folder, etc)
// and it failed, then we don't update the image to disk
free(disk_image.buffer);
return 0;
}
if (disk_image.mode == DISKMODE_MSA)
{
uint8_t *packed_msa = make_msa(arch);
if (!packed_msa)
{
free(disk_image.buffer);
return -1;
}
free(disk_image.buffer);
disk_image.buffer = packed_msa;
}
if (disk_image.mode == DISKMODE_FCOPY_CONF_ALL_SECTORS || disk_image.mode == DISKMODE_FCOPY_CONF_USED_SECTORS)
{
// Eventually here we'll just add some code to write a .dim file using "all sectors",
// unless someone reeeeeeeeally asks for "used sectors" format it's not happening
}
if (disk_image.mode == DISKMODE_FCOPY_NO_CONF)
{
// Unsure if the implementation is different here, it might be merged with the above block
}
disk_image.file_handle = fopen(arch->archname, "wb");
if (!disk_image.file_handle)
{
return -1;
}
fwrite(disk_image.buffer, (size_t)disk_image.file_size, 1, disk_image.file_handle);
free(disk_image.buffer);
fclose(disk_image.file_handle);
return 0;
}
stEntryList* findLastEntry() {
stEntryList* entry = &entryList;
while (entry->next != NULL) {
entry = entry->next;
}
return entry;
}
// In some parts of the code we get a filename in "directory format", i.e.
// something like "FILE EXT". This routine converts this to a "canonical"
// filename, i.e. "FILE.EXT"
void dir_to_canonical(char dest[13], uint8_t *src)
{
BOOL added_dot = FALSE;
for (int i = 0; i < 11; i++)
{
if (*src == ' ')
{
do
{
src++;
i++;
if (i == 11)
{
*dest = 0;
return;
}
} while (*src == ' ');
*dest++ = '.';
added_dot = TRUE;
}
*dest++ = *src++;
if (i == 7 && !added_dot && *src!=' ') *dest++ = '.';
}
*dest = 0;
}
stEntryList *new_EntryList()
{
if (!current_storage)
{
// First time run, allocate a chunk
current_storage = (ENTRYLIST_STORAGE *)malloc(65536);
if (!current_storage)
{
return NULL;
}
current_storage->prev = NULL;
current_storage->current_offset = 0;
}
if (current_storage->current_offset + sizeof(stEntryList)>STORAGE_BYTES)
{
ENTRYLIST_STORAGE *temp = current_storage;
current_storage = (ENTRYLIST_STORAGE *)malloc(65536);
if (!current_storage)
{
return NULL;
}
current_storage->prev = temp;
current_storage->current_offset = 0;
}
uint16_t offset = current_storage->current_offset;
current_storage->current_offset += sizeof(stEntryList);
return (stEntryList *)¤t_storage->data[offset];
}
uint32_t scan_files(char *path, VOLINFO *vi, char *partition_prefix)
{
uint32_t ret;
int i;
DIRINFO di;
char filename_canonical[13];
uint8_t *scratch_sector = (uint8_t *)malloc(SECTOR_SIZE);
if (!scratch_sector) return DFS_ERRMISC;
di.scratch = scratch_sector;
stEntryList *lastEntry;
ret = DFS_OpenDir(vi, (uint8_t *)path, &di);
if (ret == DFS_OK) {
i = (int)strlen(path);
for (;;) {
lastEntry = findLastEntry();
ret = DFS_GetNext(vi, &di, &(*lastEntry).de);
if (ret != DFS_OK) break;
if (lastEntry->de.name[0] == 0) continue;
if (strcmp((char *)lastEntry->de.name, ". \x10") == 0) continue;
if (strcmp((char *)lastEntry->de.name, ".. \x10") == 0) continue;
if (strlen(lastEntry->de.name) > 12)
{
// Invalid filename, mark it as illegal
strcpy(lastEntry->de.name, "ILLEGAL");
}
dir_to_canonical(filename_canonical, lastEntry->de.name);
if (lastEntry->de.attr & ATTR_VOLUME_ID) {
strcpy((char *)vi->label, filename_canonical);
continue;
}
if (lastEntry->de.attr & ATTR_DIRECTORY) {
//if we exceed MAX_PATH this image has a serious problem, so better bail out
if (strlen(path) + strlen(filename_canonical) + 1 >= MAX_PATH ||
sprintf_s((char *)lastEntry->fileWPath, MAX_PATH, "%s%s%s" DIR_SEPARATOR_STRING, partition_prefix, path, filename_canonical) == -1) {
ret = DFS_ERRMISC;
break;
}
if (i + strlen((char *)lastEntry->de.name) + 1 >= MAX_PATH ||
sprintf_s(&path[i], MAX_PATH - i, "%s" DIR_SEPARATOR_STRING, filename_canonical) == -1) {
ret = DFS_ERRMISC;
break;
}
stEntryList *new_item = new_EntryList();
if (!new_item)
{
ret = DFS_ERRMISC;
break;
}
lastEntry->next = new_item;
lastEntry->next->prev = lastEntry;
lastEntry->next->next = NULL;
lastEntry = new_item;
ret = scan_files(path, vi, partition_prefix);
if (ret != DFS_OK && ret != DFS_EOF)
{
break;
}
path[i] = 0;
}
else {
//if we exceed MAX_PATH this image has a serious problem, so better bail out
if (strlen(path) + strlen(filename_canonical) + 1 >= MAX_PATH ||
sprintf_s(lastEntry->fileWPath, MAX_PATH, "%s%s%s", partition_prefix, path, filename_canonical) == -1)
{
ret = DFS_ERRMISC;
break;
}
stEntryList *new_item = new_EntryList();
if (!new_item)
{
ret = DFS_ERRMISC;
break;
}
lastEntry->next = new_item;
lastEntry->next->prev = lastEntry;
lastEntry->next->next = NULL;
lastEntry = new_item;
}
}
}
free(scratch_sector);
return ret;
}
uint32_t OpenImage(tOpenArchiveData *wcx_archive, tArchive *arch)
{
wcx_archive->CmtBuf = 0;
wcx_archive->CmtBufSize = 0;
wcx_archive->CmtSize = 0;
wcx_archive->CmtState = 0;
wcx_archive->OpenResult = E_NO_MEMORY;// default error type
uint32_t ret= DFS_HostAttach(arch);
if (ret != J_OK)
{
wcx_archive->OpenResult = E_BAD_ARCHIVE;
return ret;
}