Debian Codegraph @

terps/scott/saga/ciderpress.c

raw symbols SCIP
1 /*
2 This is based on parts of the Ciderpress source.
3 See https://github.com/fadden/ciderpress for the full version.
4
5 Includes fragments from of a2tools by Terry Kyriacopoulos and Paul Schlyter
6 */
7
8 #include <assert.h>
9 #include <stdarg.h>
10 #include <stdint.h>
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14
15 #include "debugprint.h"
16
17 //#define NIB_VERBOSE_DEBUG
18
19 #define MIN(a, b) ((a) < (b) ? (a) : (b))
20
21 enum {
22 FILETYPE_T = 0x00,
23 FILETYPE_I = 0x01,
24 FILETYPE_A = 0x02,
25 FILETYPE_B = 0x04,
26 FILETYPE_S = 0x08,
27 FILETYPE_R = 0x10,
28 FILETYPE_X = 0x20, /* "new A" */
29 FILETYPE_Y = 0x40, /* "new B" */
30 FILETYPE_UNKNOWN = 0x100
31 };
32
33 /*
34 * ===========================================================================
35 * DiskFSDOS33
36 * ===========================================================================
37 */
38
39 const int kMaxSectors = 32;
40
41 // clang-format off
42
43 /* do we need a way to override these? */
44 static const int kVTOCTrack = 17;
45 static const int kVTOCSector = 0;
46 static const int kCatalogEntryOffset = 0x0b; // first entry in cat sect starts here
47 static const int kCatalogEntrySize = 0x23; // length in bytes of catalog entries
48 static const int kCatalogEntriesPerSect = 7; // #of entries per catalog sector
49 static const int kEntryDeleted = 0xff; // this is used for track# of deleted files
50 static const int kEntryUnused = 0x00; // this is track# in never-used entries
51 static const int kMaxTSPairs = 0x7a; // 122 entries for 256-byte sectors
52 static const int kTSOffset = 0x0c; // first T/S entry in a T/S list
53
54 // clang-format on
55
56 static const int kMaxTSIterations = 32;
57 #define kMaxFileName 30
58 #define kFileNameBufLen 31
59
60 #define kMaxCatalogSectors 64 // two tracks on a 32-sector disk
61
62 static size_t fLength = 143360;
63
64 #define kNumTracks 35
65 #define kNumSectPerTrack 16 // Is this ever 13?
66 #define kSectorSize 256
67
68 #define kChunkSize62 86 // (0x56)
69
70 #define kMaxNibbleTracks525 40 // max #of tracks on 5.25 nibble img
71 #define kTrackAllocSize 6656 // max 5.25 nibble track len; for buffers
72
73 /*
74 * ==========================================================================
75 * Block/track/sector I/O
76 * ==========================================================================
77 */
78
79 /* a T/S pair */
80 typedef struct TrackSector {
81 uint8_t track;
82 uint8_t sector;
83 } TrackSector;
84
85 TrackSector fCatalogSectors[kMaxCatalogSectors];
86
87 // clang-format off
88
89 /*
90 * Errors from the various disk image classes.
91 */
92 typedef enum DIError {
93 kDIErrNone = 0,
94
95 /* I/O request errors (should renumber/rename to match GS/OS errors?) */
96 kDIErrAccessDenied = -10,
97 kDIErrVWAccessForbidden = -11, // write access to volume forbidden
98 kDIErrSharingViolation = -12, // file is in use and not shareable
99 kDIErrNoExclusiveAccess = -13, // couldn't get exclusive access
100 kDIErrWriteProtected = -14, // disk is write protected
101 kDIErrCDROMNotSupported = -15, // access to CD-ROM drives not supptd
102 kDIErrASPIFailure = -16, // generic ASPI failure result
103 kDIErrSPTIFailure = -17, // generic SPTI failure result
104 kDIErrSCSIFailure = -18, // generic SCSI failure result
105 kDIErrDeviceNotReady = -19, // floppy or CD-ROM drive has no media
106
107 kDIErrFileNotFound = -20,
108 kDIErrForkNotFound = -21, // requested fork does not exist
109 kDIErrAlreadyOpen = -22, // already open, can't open a 2nd time
110 kDIErrFileOpen = -23, // file is open, can't delete it
111 kDIErrNotReady = -24,
112 kDIErrFileExists = -25, // file already exists
113 kDIErrDirectoryExists = -26, // directory already exists
114
115 kDIErrEOF = -30, // end-of-file reached
116 kDIErrReadFailed = -31,
117 kDIErrWriteFailed = -32,
118 kDIErrDataUnderrun = -33, // tried to read off end of the image
119 kDIErrDataOverrun = -34, // tried to write off end of the image
120 kDIErrGenericIO = -35, // generic I/O error
121
122 kDIErrOddLength = -40, // image size not multiple of sectors
123 kDIErrUnrecognizedFileFmt = -41, // file format just not recognized
124 kDIErrBadFileFormat = -42, // filename ext doesn't match contents
125 kDIErrUnsupportedFileFmt = -43, // recognized but not supported
126 kDIErrUnsupportedPhysicalFmt = -44, // (same)
127 kDIErrUnsupportedFSFmt = -45, // (and again)
128 kDIErrBadOrdering = -46, // requested sector ordering no good
129 kDIErrFilesystemNotFound = -47, // requested filesystem isn't there
130 kDIErrUnsupportedAccess = -48, // e.g. read sectors from blocks-only
131 kDIErrUnsupportedImageFeature = -49, // e.g. FDI image w/Amiga sectors
132
133 kDIErrInvalidTrack = -50, // request for invalid track number
134 kDIErrInvalidSector = -51, // request for invalid sector number
135 kDIErrInvalidBlock = -52, // request for invalid block number
136 kDIErrInvalidIndex = -53, // request with an invalid index
137
138 kDIErrDirectoryLoop = -60, // directory chain points into itself
139 kDIErrFileLoop = -61, // file sector or block alloc loops
140 kDIErrBadDiskImage = -62, // the FS on the disk image is damaged
141 kDIErrBadFile = -63, // bad file on disk image
142 kDIErrBadDirectory = -64, // bad dir on disk image
143 kDIErrBadPartition = -65, // bad partition on multi-part format
144
145 kDIErrFileArchive = -70, // file archive, not disk archive
146 kDIErrUnsupportedCompression = -71, // compression method is not supported
147 kDIErrBadChecksum = -72, // image file's checksum is bad
148 kDIErrBadCompressedData = -73, // data can't even be unpacked
149 kDIErrBadArchiveStruct = -74, // bad archive structure
150
151 kDIErrBadNibbleSectors = -80, // can't read sectors from this image
152 kDIErrSectorUnreadable = -81, // requested sector not readable
153 kDIErrInvalidDiskByte = -82, // invalid byte for encoding type
154 kDIErrBadRawData = -83, // couldn't get correct nibbles
155
156 kDIErrInvalidFileName = -90, // tried to create file with bad name
157 kDIErrDiskFull = -91, // no space left on disk
158 kDIErrVolumeDirFull = -92, // no more entries in volume dir
159 kDIErrInvalidCreateReq = -93, // CreateImage request was flawed
160 kDIErrTooBig = -94, // larger than we want to handle
161
162 /* higher-level errors */
163 kDIErrGeneric = -101,
164 kDIErrInternal = -102,
165 kDIErrMalloc = -103,
166 kDIErrInvalidArg = -104,
167 kDIErrNotSupported = -105, // feature not currently supported
168 kDIErrCancelled = -106, // an operation was cancelled by user
169
170 kDIErrNufxLibInitFailed = -110
171 } DIError;
172
173 // clang-format on
174
175 struct ringbuf_t {
176 uint8_t **buffer;
177 size_t size; //of the buffer
178 int initialized;
179 };
180
181 // Opaque circular buffer structure
182 typedef struct ringbuf_t ringbuf_t;
183 // Handle type, the way users interact with the API
184 typedef ringbuf_t *ringbuf_handle_t;
185
186 /*
187 * Nibble encode/decode description. Use no pointers here, so we
188 * store as an array and resize at will.
189 *
190 * Should we define an enum to describe whether address and data
191 * headers are standard or some wacky variant?
192 */
193 enum {
194 kNibbleAddrPrologLen = 3, // d5 aa 96
195 kNibbleAddrEpilogLen = 3, // de aa eb
196 kNibbleDataPrologLen = 3, // d5 aa ad
197 kNibbleDataEpilogLen = 3 // de aa eb
198 };
199
200 typedef struct {
201 char description[32];
202 short numSectors; // 13 or 16 (or 18?)
203
204 uint8_t addrProlog[kNibbleAddrPrologLen];
205 uint8_t addrEpilog[kNibbleAddrEpilogLen];
206 uint8_t addrChecksumSeed;
207 int addrVerifyChecksum;
208 int addrVerifyTrack;
209 int addrEpilogVerifyCount;
210
211 uint8_t dataProlog[kNibbleDataPrologLen];
212 uint8_t dataEpilog[kNibbleDataEpilogLen];
213 uint8_t dataChecksumSeed;
214 int dataVerifyChecksum;
215 int dataEpilogVerifyCount;
216 } NibbleDescr;
217
218 static const uint8_t kDiskBytes62[64] = {
219 0x96, 0x97, 0x9a, 0x9b, 0x9d, 0x9e, 0x9f, 0xa6,
220 0xa7, 0xab, 0xac, 0xad, 0xae, 0xaf, 0xb2, 0xb3,
221 0xb4, 0xb5, 0xb6, 0xb7, 0xb9, 0xba, 0xbb, 0xbc,
222 0xbd, 0xbe, 0xbf, 0xcb, 0xcd, 0xce, 0xcf, 0xd3,
223 0xd6, 0xd7, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde,
224 0xdf, 0xe5, 0xe6, 0xe7, 0xe9, 0xea, 0xeb, 0xec,
225 0xed, 0xee, 0xef, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6,
226 0xf7, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
227 };
228
229 /* static data tables */
230 static uint8_t *kInvDiskBytes62 = NULL;
231 #define kInvInvalidValue 0xff
232
233 uint8_t *fNibbleTrackBuf = NULL; // allocated on heap
234
235 int fNibbleTrackLoaded = -1; // track currently in buffer
236
237 static uint8_t *rawdata = NULL;
238 static size_t rawdatalen = 0;
239
240 typedef enum { // format of the image data stream
241 kPhysicalFormatUnknown = 0,
242 kPhysicalFormatSectors = 1, // sequential 256-byte sectors (13/16/32)
243 kPhysicalFormatNib525_6656 = 2, // 5.25" disk ".nib" (6656 bytes/track)
244 kPhysicalFormatNib525_Var = 4, // 5.25" disk (variable len, e.g. ".app")
245 } PhysicalFormat;
246
247 const int kTrackLenNib525 = 6656;
248 const int kTrackLenNb2525 = 6384;
249
250 PhysicalFormat physical = kPhysicalFormatNib525_6656;
251
252 struct A2FileDOS {
253 int starting_block;
254 int fTSListTrack;
255 int fTSListSector;
256 int fLocked;
257 int fFileType;
258 uint8_t fRawFileName[kFileNameBufLen];
259 uint8_t fFileName[kFileNameBufLen];
260 int fLengthInSectors;
261 int fCatTStrack;
262 int fCatTSsector;
263 int fCatEntryNum;
264 TrackSector *tsList;
265 int tsCount;
266 TrackSector *indexList;
267 int indexCount;
268 int fOffset;
269 int fOpenEOF;
270 int fOpenSectorsUsed;
271 struct A2FileDOS *prev;
272 struct A2FileDOS *next;
273 };
274
275 typedef struct A2FileDOS A2FileDOS;
276
277 A2FileDOS *firstfile = NULL;
278 A2FileDOS *lastfile = NULL;
279
280 static int fFirstCatTrack;
281 static int fFirstCatSector;
282 static int fVTOCVolumeNumber;
283 static int fVTOCNumTracks;
284 static int fVTOCNumSectors;
285
286 uint8_t fVTOC[kSectorSize];
287
288 static void *MemAlloc(size_t size)
289 {
290 void *t = (void *)malloc(size);
291 if (t == NULL) {
292 fprintf(stderr, "Out of memory\n");
293 exit(1);
294 }
295 return (t);
296 }
297
298 static uint8_t access_ringbuf(ringbuf_handle_t ringbuf, int index)
299 {
300 if (ringbuf == NULL || ringbuf->initialized == 0 || ringbuf->buffer == NULL || *(ringbuf->buffer) == NULL) {
301 debug_print("ERROR! Ringbuf not ready!\n");
302 return -1;
303 }
304
305 if (index >= ringbuf->size)
306 index -= ringbuf->size;
307 if (index < 0)
308 index = ringbuf->size - index;
309 uint8_t *buffer = *(ringbuf->buffer);
310
311 return buffer[index];
312 }
313
314 /*
315 * Compute tables to convert disk bytes back to values.
316 *
317 * Should be called once, at DLL initialization time.
318 */
319 static void CalcNibbleInvTables(void)
320 {
321 unsigned int i;
322
323 if (kInvDiskBytes62 != NULL)
324 return;
325
326 kInvDiskBytes62 = MemAlloc(256);
327
328 memset(kInvDiskBytes62, kInvInvalidValue, 256);
329 for (i = 0; i < sizeof(kDiskBytes62); i++) {
330 assert(kDiskBytes62[i] >= 0x96);
331 kInvDiskBytes62[kDiskBytes62[i]] = i;
332 }
333 }
334
335 static uint16_t ConvFrom44(uint8_t val1, uint8_t val2)
336 {
337 return ((val1 << 1) | 0x01) & val2;
338 }
339
340 /*
341 * Decode the values in the address field.
342 */
343 static void DecodeAddr(ringbuf_handle_t ringbuffer, int offset,
344 short *pVol, short *pTrack, short *pSector, short *pChksum)
345 {
346 //unsigned int vol, track, sector, chksum;
347
348 *pVol = ConvFrom44(access_ringbuf(ringbuffer, offset), access_ringbuf(ringbuffer, offset + 1));
349 *pTrack = ConvFrom44(access_ringbuf(ringbuffer, offset + 2), access_ringbuf(ringbuffer, offset + 3));
350 *pSector = ConvFrom44(access_ringbuf(ringbuffer, offset + 4), access_ringbuf(ringbuffer, offset + 5));
351 *pChksum = ConvFrom44(access_ringbuf(ringbuffer, offset + 6), access_ringbuf(ringbuffer, offset + 7));
352 }
353
354 const NibbleDescr nibbleDescr = {
355 "DOS 3.3 Standard",
356 16, // number of sectors
357 { 0xd5, 0xaa, 0x96 }, // addrProlog
358 { 0xde, 0xaa, 0xeb }, // addrEpilog
359 0x00, // checksum seed
360 0, // verify checksum
361 0, // verify track
362 2, // epilog verify count
363 { 0xd5, 0xaa, 0xad }, // dataProlog
364 { 0xde, 0xaa, 0xeb }, // dataEpilog
365 0x00, // checksum seed
366 0, // verify checksum
367 2, // epilog verify count
368 };
369
370 const NibbleDescr *pNibbleDescr = &nibbleDescr;
371
372 /*
373 * Find the start of the data field of a sector in nibblized data.
374 *
375 * Returns the index start on success or -1 on failure.
376 */
377 static int FindNibbleSectorStart(ringbuf_handle_t ringbuffer, int track,
378 int sector, int *pVol)
379 {
380 //DIError dierr;
381 long trackLen = ringbuffer->size;
382 const int kMaxDataReach = trackLen; // fairly arbitrary
383
384 assert(sector >= 0 && sector < 16);
385
386 int i;
387
388 for (i = 0; i < trackLen; i++) {
389 int foundAddr = 0;
390
391 if (access_ringbuf(ringbuffer, i) == pNibbleDescr->addrProlog[0] && access_ringbuf(ringbuffer, i + 1) == pNibbleDescr->addrProlog[1] && access_ringbuf(ringbuffer, i + 2) == pNibbleDescr->addrProlog[2]) {
392 foundAddr = 1;
393 }
394
395 if (foundAddr) {
396 //i += 3;
397
398 /* found the address header, decode the address */
399 short hdrVol, hdrTrack, hdrSector, hdrChksum;
400 DecodeAddr(ringbuffer, i + 3, &hdrVol, &hdrTrack, &hdrSector,
401 &hdrChksum);
402
403 if (pNibbleDescr->addrVerifyTrack && track != hdrTrack) {
404 debug_print("Track mismatch");
405 debug_print(" Track mismatch (T=%d) got T=%d,S=%d", track, hdrTrack, hdrSector);
406 continue;
407 }
408
409 if (pNibbleDescr->addrVerifyChecksum) {
410 if ((pNibbleDescr->addrChecksumSeed ^ hdrVol ^ hdrTrack ^ hdrSector ^ hdrChksum) != 0) {
411 debug_print(" Addr checksum mismatch (want T=%d,S=%d, got T=%d,S=%d)", track, sector, hdrTrack, hdrSector);
412 continue;
413 }
414 }
415
416 i += 3;
417
418 int j;
419 for (j = 0; j < pNibbleDescr->addrEpilogVerifyCount; j++) {
420 if (access_ringbuf(ringbuffer, i + 8 + j) != pNibbleDescr->addrEpilog[j]) {
421 //debug_print(" Bad epilog byte %d (%02x vs %02x)",
422 // j, buffer[i+8+j], pNibbleDescr->addrEpilog[j]);
423 break;
424 }
425 }
426 if (j != pNibbleDescr->addrEpilogVerifyCount)
427 continue;
428
429 #ifdef NIB_VERBOSE_DEBUG
430 debug_print(" Good header, T=%d,S=%d (looking for T=%d,S=%d)",
431 hdrTrack, hdrSector, track, sector);
432 #endif
433
434 if (sector != hdrSector)
435 continue;
436
437 /*
438 * Scan forward and look for data prolog. We want to limit
439 * the reach of our search so we don't blunder into the data
440 * field of the next sector.
441 */
442 for (j = 0; j < kMaxDataReach; j++) {
443 if (access_ringbuf(ringbuffer, i + j) == pNibbleDescr->dataProlog[0] && access_ringbuf(ringbuffer, i + j + 1) == pNibbleDescr->dataProlog[1] && access_ringbuf(ringbuffer, i + j + 2) == pNibbleDescr->dataProlog[2]) {
444 *pVol = hdrVol;
445 int idx = i + j + 3;
446 while (idx >= ringbuffer->size)
447 idx -= ringbuffer->size;
448 return idx;
449 }
450 }
451 }
452 }
453
454 #ifdef NIB_VERBOSE_DEBUG
455 debug_print(" Couldn't find T=%d,S=%d", track, sector);
456 #endif
457 return -1;
458 }
459
460 /*
461 * Decode 6&2 encoding.
462 */
463 static DIError DecodeNibbleData(ringbuf_handle_t ringbuffer, int idx,
464 uint8_t *sctBuf)
465 {
466 uint8_t twos[kChunkSize62 * 3]; // 258
467 int chksum = pNibbleDescr->dataChecksumSeed;
468 uint8_t decodedVal;
469 int i;
470
471 /*
472 * Pull the 342 bytes out, convert them from disk bytes to 6-bit
473 * values, and arrange them into a DOS-like pair of buffers.
474 */
475 for (i = 0; i < kChunkSize62; i++) {
476 decodedVal = kInvDiskBytes62[access_ringbuf(ringbuffer, idx++)];
477 if (decodedVal == kInvInvalidValue)
478 return kDIErrInvalidDiskByte;
479 assert(decodedVal < sizeof(kDiskBytes62));
480
481 chksum ^= decodedVal;
482 twos[i] = ((chksum & 0x01) << 1) | ((chksum & 0x02) >> 1);
483 twos[i + kChunkSize62] = ((chksum & 0x04) >> 1) | ((chksum & 0x08) >> 3);
484 twos[i + kChunkSize62 * 2] = ((chksum & 0x10) >> 3) | ((chksum & 0x20) >> 5);
485 }
486
487 for (i = 0; i < 256; i++) {
488 decodedVal = kInvDiskBytes62[access_ringbuf(ringbuffer, idx++)];
489 if (decodedVal == kInvInvalidValue)
490 return kDIErrInvalidDiskByte;
491 assert(decodedVal < sizeof(kDiskBytes62));
492
493 chksum ^= decodedVal;
494 sctBuf[i] = (chksum << 2) | twos[i];
495 }
496
497 /*
498 * Grab the 343rd byte (the checksum byte) and see if we did this
499 * right.
500 */
501 debug_print("Dec checksum value is 0x%02x\n", chksum);
502 decodedVal = kInvDiskBytes62[access_ringbuf(ringbuffer, idx++)];
503 if (decodedVal == kInvInvalidValue)
504 return kDIErrInvalidDiskByte;
505 assert(decodedVal < sizeof(kDiskBytes62));
506 chksum ^= decodedVal;
507
508 if (pNibbleDescr->dataVerifyChecksum && chksum != 0) {
509 debug_print(" NIB bad data checksum");
510 return kDIErrBadChecksum;
511 }
512 return kDIErrNone;
513 }
514
515 /*
516 * Copy a chunk of bytes out of the disk image.
517 *
518 * (This is the lowest-level read routine in this class.)
519 */
520 static DIError CopyBytesOut(void *buf, size_t offset, int size)
521 {
522 // if (offset + size > rawdatalen)
523 // return kDIErrDataUnderrun;
524 memcpy(buf, rawdata + offset, size);
525 return kDIErrNone;
526 }
527
528 /*
529 * Handle sector order conversions.
530 */
531 static DIError CalcSectorAndOffset(long track, int sector, size_t *pOffset, int *pNewSector)
532 {
533 /*
534 * Sector order conversions. No table is needed for Copy ][+ format,
535 * which is equivalent to "physical".
536 */
537
538 static const int dos2raw[16] = {
539 0, 13, 11, 9, 7, 5, 3, 1, 14, 12, 10, 8, 6, 4, 2, 15
540 };
541
542 if (track < 0 || track >= kNumTracks) {
543 debug_print(" DI read invalid track %ld", track);
544 return kDIErrInvalidTrack;
545 }
546 if (sector < 0 || sector >= kNumSectPerTrack) {
547 debug_print(" DI read invalid sector %d", sector);
548 return kDIErrInvalidSector;
549 }
550
551 size_t offset;
552 int newSector = -1;
553
554 /*
555 * 16-sector disks write sectors in ascending order and then remap
556 * them with a translation table.
557 */
558 offset = track * kNumSectPerTrack * kSectorSize;
559 if (sector >= 16) {
560 offset += 16 * kSectorSize;
561 sector -= 16;
562 }
563 assert(sector >= 0 && sector < 16);
564
565 /* convert request to "raw" sector number */
566
567 if (physical == kPhysicalFormatNib525_6656)
568 newSector = dos2raw[sector];
569 else
570 newSector = sector;
571
572 offset += newSector * kSectorSize;
573
574 *pOffset = offset;
575 *pNewSector = newSector;
576 return kDIErrNone;
577 }
578
579 /*
580 * Load a nibble track into our track buffer.
581 */
582 static DIError LoadNibbleTrack(long track, long *pTrackLen)
583 {
584 DIError dierr = kDIErrNone;
585 long offset;
586 assert(track >= 0 && track < kMaxNibbleTracks525);
587
588 if (physical != kPhysicalFormatNib525_6656)
589 return kDIErrNotSupported;
590
591 *pTrackLen = kTrackLenNib525;
592 offset = kTrackLenNib525 * track;
593 assert(*pTrackLen > 0);
594 assert(offset >= 0);
595
596 if (track == fNibbleTrackLoaded) {
597 #ifdef NIB_VERBOSE_DEBUG
598 debug_print(" DI track %ld already loaded\n", track);
599 #endif
600 return kDIErrNone;
601 } else {
602 debug_print(" DI loading track %ld\n", track);
603 }
604
605 /* invalidate in case we fail with partial read */
606 fNibbleTrackLoaded = -1;
607
608 /* alloc track buffer if needed */
609 if (fNibbleTrackBuf == NULL) {
610 fNibbleTrackBuf = MemAlloc(kTrackAllocSize);
611 }
612
613 /*
614 * Read the entire track into memory.
615 */
616 dierr = CopyBytesOut(fNibbleTrackBuf, offset, *pTrackLen);
617 if (dierr != kDIErrNone)
618 return dierr;
619
620 fNibbleTrackLoaded = track;
621
622 return dierr;
623 }
624
625 /*
626 * Read a sector from a nibble image.
627 *
628 * While fNumTracks is valid, fNumSectPerTrack is a little flaky, because
629 * in theory each track could be formatted differently.
630 */
631 static DIError ReadNibbleSector(long track, int sector, uint8_t *buf)
632 {
633 if (pNibbleDescr == NULL) {
634 /* disk has no recognizable sectors */
635 debug_print(" DI ReadNibbleSector: pNibbleDescr is NULL, returning failure");
636 return kDIErrBadNibbleSectors;
637 }
638 if (sector >= pNibbleDescr->numSectors) {
639 /* e.g. trying to read sector 14 on a 13-sector disk */
640 debug_print(" DI ReadNibbleSector: bad sector number request");
641 return kDIErrInvalidSector;
642 }
643
644 assert(pNibbleDescr != NULL);
645 assert(track >= 0 && track < kNumTracks);
646 assert(sector >= 0 && sector < pNibbleDescr->numSectors);
647
648 DIError dierr = kDIErrNone;
649 long trackLen;
650 int sectorIdx, vol;
651
652 dierr = LoadNibbleTrack(track, &trackLen);
653 if (dierr != kDIErrNone) {
654 debug_print(" DI ReadNibbleSector: LoadNibbleTrack %ld failed", track);
655 return dierr;
656 }
657
658 ringbuf_t circularbuf;
659 ringbuf_handle_t ringbuffer = &circularbuf;
660 ringbuffer->size = trackLen;
661 ringbuffer->buffer = &fNibbleTrackBuf;
662 ringbuffer->initialized = 1;
663
664 sectorIdx = FindNibbleSectorStart(ringbuffer, track, sector,
665 &vol);
666 if (sectorIdx < 0) {
667 return kDIErrSectorUnreadable;
668 }
669
670 dierr = DecodeNibbleData(ringbuffer, sectorIdx, buf);
671
672 return dierr;
673 }
674
675 void InitNibImage(uint8_t *data, size_t datasize)
676 {
677 if (kInvDiskBytes62 == NULL)
678 CalcNibbleInvTables();
679
680 rawdata = data;
681 rawdatalen = datasize;
682 fNibbleTrackLoaded = -1;
683
684 physical = kPhysicalFormatNib525_6656;
685 }
686
687 void InitDskImage(uint8_t *data, size_t datasize)
688 {
689 rawdata = data;
690 rawdatalen = datasize;
691
692 physical = kPhysicalFormatSectors;
693 }
694
695 void FreeDiskImage(void)
696 {
697 rawdata = NULL;
698 rawdatalen = 0;
699 fNibbleTrackLoaded = -1;
700 if (fNibbleTrackBuf != NULL) {
701 free(fNibbleTrackBuf);
702 fNibbleTrackBuf = NULL;
703 }
704 while (firstfile != NULL) {
705 A2FileDOS *nextfile = firstfile->next;
706 if (firstfile->tsList != NULL)
707 free(firstfile->tsList);
708 if (firstfile->indexList != NULL)
709 free(firstfile->indexList);
710 free(firstfile);
711 firstfile = nextfile;
712 }
713 lastfile = NULL;
714 }
715
716 uint8_t *ReadImageFromNib(size_t offset, size_t size, uint8_t *data, size_t datasize)
717 {
718 uint8_t *result = MemAlloc(size);
719
720 rawdata = data;
721 rawdatalen = datasize;
722
723 physical = kPhysicalFormatNib525_6656;
724
725 uint8_t buf[0x100];
726
727 size_t pOffset;
728 int pNewSector;
729 int track = offset / 0x1000;
730 int sector = (offset % 0x1000) / 0x100;
731
732 for (int remaining = (int)size; remaining > 0; remaining -= 0x100) {
733 DIError error = CalcSectorAndOffset(track, sector, &pOffset, &pNewSector);
734 if (error != kDIErrNone) {
735 fprintf(stderr, "Error while calculating sector and offset of nib!\n");
736 free(result);
737 return NULL;
738 }
739 error = ReadNibbleSector(track, pNewSector, buf);
740 if (error != kDIErrNone) {
741 fprintf(stderr, "Error while reading nibble sector!\n");
742 free(result);
743 return NULL;
744 }
745 sector++;
746 if (sector > 15) {
747 sector = 0;
748 track++;
749 }
750 memcpy(result + (size - remaining), buf, MIN(0x100, remaining));
751 }
752
753 return result;
754 }
755
756 /*
757 * Read the specified track and sector, adjusting for sector ordering as
758 * appropriate.
759 *
760 * Copies 256 bytes into "*buf".
761 *
762 * Returns 0 on success, nonzero on failure.
763 */
764 static DIError ReadTrackSector(long track, int sector, void *buf)
765 {
766 DIError dierr;
767 size_t offset;
768 int newSector = -1;
769
770 if (buf == NULL)
771 return kDIErrInvalidArg;
772
773 dierr = CalcSectorAndOffset(track, sector,
774 &offset, &newSector);
775 if (dierr != kDIErrNone)
776 return dierr;
777
778 assert(offset + kSectorSize <= fLength);
779
780 if (physical == kPhysicalFormatNib525_6656)
781 dierr = ReadNibbleSector(track, newSector, buf);
782 else
783 dierr = CopyBytesOut(buf, offset, kSectorSize);
784
785 return dierr;
786 }
787
788 static void AddFileToList(A2FileDOS *file)
789 {
790 if (firstfile == NULL) {
791 firstfile = file;
792 } else if (lastfile == NULL) {
793 lastfile = file;
794 firstfile->next = file;
795 file->prev = firstfile;
796 } else {
797 lastfile->next = file;
798 file->prev = lastfile;
799 lastfile = file;
800 }
801 }
802
803 /*
804 * Convert high ASCII to low ASCII.
805 *
806 * Some people put inverse and flashing text into filenames, not to mention
807 * control characters, so we have to cope with those too.
808 *
809 * We modify the first "len" bytes of "buf" in place.
810 */
811 static void LowerASCII(uint8_t filename[kFileNameBufLen])
812 {
813
814 int len = kMaxFileName;
815 uint8_t *buf = filename;
816 while (len--) {
817 if (*buf & 0x80) {
818 if (*buf >= 0xa0)
819 *buf &= 0x7f;
820 else
821 *buf = (*buf & 0x7f) + 0x20;
822 } else
823 *buf = ((*buf & 0x3f) ^ 0x20) + 0x20;
824
825 buf++;
826 }
827 }
828
829 /*
830 * Trim the spaces off the end of a filename.
831 *
832 * Assumes the filename has already been converted to low ASCII.
833 */
834 static void TrimTrailingSpaces(uint8_t filename[kFileNameBufLen])
835 {
836 uint8_t *lastspc = filename + strlen((char *)filename);
837
838 assert(*lastspc == '\0');
839
840 while (--lastspc) {
841 if (*lastspc != ' ')
842 break;
843 }
844
845 *(lastspc + 1) = '\0';
846 }
847
848 /*
849 * "Fix" a DOS3.3 filename. Convert DOS-ASCII to normal ASCII, and strip
850 * trailing spaces.
851 */
852 static void FixFilename(uint8_t filename[kFileNameBufLen])
853 {
854 LowerASCII(filename);
855 TrimTrailingSpaces(filename);
856 }
857
858 /*
859 * Extract the track/sector pairs from the TS list in "sctBuf". The entries
860 * are copied to "tsList", which is assumed to have enough space to hold
861 * at least kMaxTSPairs entries.
862 *
863 * The last non-zero entry will be identified and stored in "*pLastNonZero".
864 * If all entries are zero, it will be set to -1.
865 *
866 * Sometimes files will have junk at the tail end of an otherwise valid
867 * T/S list. We can't just stop when we hit the first (0,0) entry because
868 * that'll screw up random-access text file handling. What we can do is
869 * try to detect the situation, and mark the file as "suspicious" without
870 * returning an error if we see it.
871 *
872 * If a TS entry appears to be invalid, this returns an error after all
873 * entries have been copied. If it looks to be partially valid, only the
874 * valid parts are copied out, with the rest zeroed.
875 */
876 static DIError ExtractTSPairs(A2FileDOS *DOSFile, const uint8_t *sctBuf, TrackSector *tsList,
877 int *pLastNonZero)
878 {
879 DIError dierr = kDIErrNone;
880 // const DiskImg* pDiskImg = fpDiskFS->GetDiskImg();
881 const uint8_t *ptr;
882 int i, track, sector;
883
884 *pLastNonZero = -1;
885 memset(tsList, 0, sizeof(TrackSector) * kMaxTSPairs);
886
887 ptr = &sctBuf[kTSOffset]; // offset of first T/S entry (0x0c)
888
889 for (i = 0; i < kMaxTSPairs; i++) {
890 track = *ptr++;
891 sector = *ptr++;
892
893 if (dierr == kDIErrNone && (track >= kNumTracks || sector >= kNumSectPerTrack || (track == 0 && sector != 0))) {
894 debug_print(" DOS33 invalid T/S %d,%d in '%s'\n", track, sector,
895 DOSFile->fFileName);
896
897 if (i > 0 && tsList[i - 1].track == 0 && tsList[i - 1].sector == 0) {
898 debug_print(" T/S list looks partially valid\n");
899 goto bail; // quit immediately
900 } else {
901 dierr = kDIErrBadFile;
902 // keep going, just so caller has the full set to stare at
903 }
904 }
905
906 if (track != 0 || sector != 0)
907 *pLastNonZero = i;
908
909 tsList[i].track = track;
910 tsList[i].sector = sector;
911 }
912
913 bail:
914 return dierr;
915 }
916
917 const int kDefaultTSAlloc = 2;
918 const int kDefaultIndexAlloc = 8;
919
920 /*
921 * Load the T/S list for this file.
922 *
923 * A single T/S sector holds 122 entries, enough to store a 30.5K file.
924 * It's very unlikely that a file will need more than two, although it's
925 * possible for a random-access text file to have a very large number of
926 * entries.
927 *
928 * If "pIndexList" and "pIndexCount" are non-NULL, the list of index blocks is
929 * also loaded.
930 *
931 * It's entirely possible to get a large T/S list back that is filled
932 * entirely with zeroes. This can happen if we have a large set of T/S
933 * index sectors that are all zero. We have to leave space for them so
934 * that the Write function can use the existing allocated index blocks.
935 *
936 * THOUGHT: we may want to use the file type to tighten this up a bit.
937 * For example, we're currently very careful around random-access text
938 * files, but if the file doesn't have type 'T' then random access is
939 * impossible. Currently this isn't a problem, but for e.g. T/S lists
940 * with garbage at the end would could deal with the problem more generally.
941 */
942 static DIError LoadTSList(A2FileDOS *DOSFile)
943 {
944 DIError dierr = kDIErrNone;
945
946 TrackSector *tsList = NULL;
947 TrackSector *indexList = NULL;
948 int tsCount, tsAlloc;
949 int indexCount, indexAlloc;
950 uint8_t sctBuf[kSectorSize];
951 int track, sector, iterations;
952
953 debug_print("--- DOS loading T/S list for '%s'\n", DOSFile->fFileName);
954
955 /* over-alloc for small files to reduce reallocs */
956 tsAlloc = kMaxTSPairs * kDefaultTSAlloc;
957 tsList = MemAlloc(tsAlloc * sizeof(TrackSector));
958 tsCount = 0;
959
960 indexAlloc = kDefaultIndexAlloc;
961 indexList = MemAlloc(indexAlloc * sizeof(TrackSector));
962 indexCount = 0;
963
964 /* get the first T/S sector for this file */
965 track = DOSFile->fTSListTrack;
966 sector = DOSFile->fTSListSector;
967 if (track >= kNumTracks || sector >= kNumSectPerTrack) {
968 debug_print(" DOS33 invalid initial T/S %d,%d in '%s'\n", track, sector,
969 DOSFile->fFileName);
970 dierr = kDIErrBadFile;
971 goto bail;
972 }
973
974 /*
975 * Run through the set of t/s pairs.
976 */
977 iterations = 0;
978 do {
979 uint16_t sectorOffset;
980 int lastNonZero;
981
982 /*
983 * Add the current T/S sector to the index list.
984 */
985 if (indexCount == indexAlloc) {
986 debug_print("+++ expanding index list\n");
987 TrackSector *newList;
988 indexAlloc += kDefaultIndexAlloc;
989 newList = MemAlloc(indexAlloc * sizeof(TrackSector));
990 memcpy(newList, indexList, indexCount * sizeof(TrackSector));
991 free(indexList);
992 indexList = newList;
993 }
994 indexList[indexCount].track = track;
995 indexList[indexCount].sector = sector;
996 indexCount++;
997
998 dierr = ReadTrackSector(track, sector, sctBuf);
999 if (dierr != kDIErrNone)
1000 goto bail;
1001
1002 /* grab next track/sector */
1003 track = sctBuf[0x01];
1004 sector = sctBuf[0x02];
1005 sectorOffset = sctBuf[0x05] + sctBuf[0x06] * 256;
1006
1007 /* if T/S link is bogus, whole sector is probably bad */
1008 if (track >= kNumTracks || sector >= kNumSectPerTrack) {
1009 // bogus T/S, mark file as damaged and stop
1010 debug_print(" DOS33 invalid T/S link %d,%d in '%s'\n", track, sector,
1011 DOSFile->fFileName);
1012 dierr = kDIErrBadFile;
1013 goto bail;
1014 }
1015 if ((sectorOffset % kMaxTSPairs) != 0) {
1016 debug_print(" DOS33 invalid T/S header sector offset %u in '%s'\n",
1017 sectorOffset, DOSFile->fFileName);
1018 // not fatal, just weird
1019 }
1020
1021 /*
1022 * Make sure we have enough room to hold an entire sector full of
1023 * T/S pairs in the list.
1024 */
1025 if (tsCount + kMaxTSPairs > tsAlloc) {
1026 debug_print("+++ expanding ts list\n");
1027 TrackSector *newList;
1028 tsAlloc += kMaxTSPairs * kDefaultTSAlloc;
1029 newList = MemAlloc(tsAlloc * sizeof(TrackSector));
1030 memcpy(newList, tsList, tsCount * sizeof(TrackSector));
1031 free(tsList);
1032 tsList = newList;
1033 }
1034
1035 /*
1036 * Add the entries. If there's another T/S list linked, we just
1037 * grab the entire sector. If not, we grab every entry until the
1038 * last 0,0. (Can't stop at the first (0,0), or we'll drop a
1039 * piece of a random access text file.)
1040 */
1041 dierr = ExtractTSPairs(DOSFile, sctBuf, &tsList[tsCount], &lastNonZero);
1042 if (dierr != kDIErrNone)
1043 goto bail;
1044
1045 if (track != 0 && sector != 0) {
1046 /* more T/S lists to come, so we keep all entries */
1047 tsCount += kMaxTSPairs;
1048 } else {
1049 /* this was the last one */
1050 if (lastNonZero == -1) {
1051 /* this is ALWAYS the case for a newly-created file */
1052 //LOGI(" DOS33 odd -- last T/S sector of '%s' was empty",
1053 // GetPathName());
1054 }
1055 tsCount += lastNonZero + 1;
1056 }
1057
1058 iterations++; // watch for infinite loops
1059 } while (!(track == 0 && sector == 0) && iterations < kMaxTSIterations);
1060
1061 if (iterations == kMaxTSIterations) {
1062 dierr = kDIErrFileLoop;
1063 goto bail;
1064 }
1065
1066 DOSFile->tsList = tsList;
1067 DOSFile->tsCount = tsCount;
1068 tsList = NULL;
1069
1070 if (DOSFile->indexList != NULL) {
1071 DOSFile->indexList = indexList;
1072 DOSFile->indexCount = indexCount;
1073 indexList = NULL;
1074 }
1075
1076 bail:
1077 free(tsList);
1078 free(indexList);
1079 return dierr;
1080 }
1081
1082 /*
1083 * Read data from the current offset.
1084 *
1085 * Files read back as they would from ProDOS, i.e. if you read a binary
1086 * file you won't see the 4 bytes of length and address.
1087 */
1088 static DIError Read(A2FileDOS *pFile, uint8_t *buf, size_t len, size_t *pActual)
1089 {
1090 debug_print(" DOS reading %lu bytes from '%s' (offset=%ld)\n",
1091 (unsigned long)len, pFile->fFileName, (long)pFile->fOffset);
1092
1093 /*
1094 * Don't allow them to read past the end of the file. The length value
1095 * stored in pFile->fLength already has pFile->fDataOffset subtracted
1096 * from the actual data length, so don't factor it in again.
1097 */
1098 if (pFile->fOffset + (long)len > pFile->fOpenEOF) {
1099 if (pActual == NULL)
1100 return kDIErrDataUnderrun;
1101 len = (size_t)(pFile->fOpenEOF - pFile->fOffset);
1102 }
1103 if (pActual != NULL)
1104 *pActual = len;
1105 long incrLen = len;
1106
1107 DIError dierr = kDIErrNone;
1108 uint8_t sctBuf[kSectorSize];
1109 size_t actualOffset = pFile->fOffset; //+ pFile->fDataOffset; // adjust for embedded len
1110 int tsIndex = (int)(actualOffset / kSectorSize);
1111 int bufOffset = (int)(actualOffset % kSectorSize); // (& 0xff)
1112 size_t thisCount;
1113
1114 if (len == 0)
1115 return kDIErrNone;
1116 assert(pFile->fOpenEOF != 0);
1117
1118 assert(tsIndex >= 0 && tsIndex < pFile->tsCount);
1119
1120 /* could be more clever in here and avoid double-buffering */
1121 while (len) {
1122 if (tsIndex >= pFile->tsCount) {
1123 /* should've caught this earlier */
1124 debug_print(" DOS ran off the end (fTSCount=%d). len == %zu\n", pFile->tsCount, len);
1125 return kDIErrDataUnderrun;
1126 }
1127
1128 if (pFile->tsList[tsIndex].track == 0 && pFile->tsList[tsIndex].sector == 0) {
1129 //LOGI(" DOS sparse sector T=%d S=%d",
1130 // TSTrack(fTSList[tsIndex]), TSSector(fTSList[tsIndex]));
1131 memset(sctBuf, 0, sizeof(sctBuf));
1132 } else {
1133 dierr = ReadTrackSector(pFile->tsList[tsIndex].track, pFile->tsList[tsIndex].sector, sctBuf);
1134 if (dierr != kDIErrNone) {
1135 debug_print(" DOS error reading file '%s'\n", pFile->fFileName);
1136 return dierr;
1137 }
1138 }
1139 thisCount = kSectorSize - bufOffset;
1140 if (thisCount > len)
1141 thisCount = len;
1142 memcpy(buf, sctBuf + bufOffset, thisCount);
1143 len -= thisCount;
1144 buf = buf + thisCount;
1145
1146 bufOffset = 0;
1147 tsIndex++;
1148 }
1149
1150 pFile->fOffset += incrLen;
1151
1152 return dierr;
1153 }
1154
1155 /*
1156 * Set up state for this file.
1157 */
1158 static DIError Open(A2FileDOS *pOpenFile)
1159 {
1160 DIError dierr = kDIErrNone;
1161
1162 dierr = LoadTSList(pOpenFile);
1163 if (dierr != kDIErrNone) {
1164 debug_print("DOS33 unable to load TS for '%s' open\n", pOpenFile->fFileName);
1165 goto bail;
1166 }
1167
1168 pOpenFile->fOffset = 0;
1169 pOpenFile->fOpenEOF = fLength;
1170 pOpenFile->fOpenSectorsUsed = pOpenFile->fLengthInSectors;
1171
1172 // fpOpenFile = pOpenFile; // add it to our single-member "open file set"
1173 // *ppOpenFile = pOpenFile;
1174 // pOpenFile = NULL;
1175 //
1176 bail:
1177 // delete pOpenFile;
1178 return dierr;
1179 }
1180
1181 /*
1182 * Process the list of files in one sector of the catalog.
1183 *
1184 * Pass in the track, sector, and the contents of that track and sector.
1185 * (We only use "catTrack" and "catSect" to fill out some fields.)
1186 */
1187 static DIError ProcessCatalogSector(int catTrack, int catSect,
1188 const uint8_t *sctBuf)
1189 {
1190 A2FileDOS *pFile;
1191 const uint8_t *pEntry;
1192 int i;
1193
1194 pEntry = &sctBuf[kCatalogEntryOffset];
1195
1196 for (i = 0; i < kCatalogEntriesPerSect; i++) {
1197 if (pEntry[0x00] != kEntryUnused && pEntry[0x00] != kEntryDeleted) {
1198 pFile = MemAlloc(sizeof(A2FileDOS));
1199 pFile->prev = NULL;
1200 pFile->next = NULL;
1201
1202 pFile->fTSListTrack = pEntry[0x00];
1203 pFile->fTSListSector = pEntry[0x01];
1204 pFile->fLocked = (pEntry[0x02] & 0x80) != 0;
1205 switch (pEntry[0x02] & 0x7f) {
1206 case 0x00:
1207 pFile->fFileType = FILETYPE_T;
1208 break;
1209 case 0x01:
1210 pFile->fFileType = FILETYPE_I;
1211 break;
1212 case 0x02:
1213 pFile->fFileType = FILETYPE_A;
1214 break;
1215 case 0x04:
1216 pFile->fFileType = FILETYPE_B;
1217 break;
1218 case 0x08:
1219 pFile->fFileType = FILETYPE_S;
1220 break;
1221 case 0x10:
1222 pFile->fFileType = FILETYPE_R;
1223 break;
1224 case 0x20:
1225 pFile->fFileType = FILETYPE_A;
1226 break;
1227 case 0x40:
1228 pFile->fFileType = FILETYPE_B;
1229 break;
1230 default:
1231 /* some odd arrangement of bit flags? */
1232 debug_print(" DOS33 peculiar filetype byte 0x%02x\n", pEntry[0x02]);
1233 pFile->fFileType = FILETYPE_UNKNOWN;
1234 break;
1235 }
1236
1237 memcpy(pFile->fRawFileName, &pEntry[0x03], kMaxFileName);
1238 pFile->fRawFileName[kMaxFileName] = '\0';
1239
1240 memcpy(pFile->fFileName, &pEntry[0x03], kMaxFileName);
1241 pFile->fFileName[kMaxFileName] = '\0';
1242 FixFilename(pFile->fFileName);
1243
1244 debug_print("File name: %s\n", pFile->fFileName);
1245
1246 pFile->fLengthInSectors = pEntry[0x21];
1247 pFile->fLengthInSectors |= (uint16_t)pEntry[0x22] << 8;
1248
1249 pFile->fCatTStrack = catTrack;
1250 pFile->fCatTSsector = catSect;
1251 pFile->fCatEntryNum = i;
1252
1253 pFile->tsList = NULL;
1254 pFile->tsCount = 0;
1255 pFile->indexList = NULL;
1256 pFile->indexCount = 0;
1257 pFile->fOffset = 0;
1258 pFile->fOpenEOF = 0;
1259 pFile->fOpenSectorsUsed = 0;
1260
1261 AddFileToList(pFile);
1262 }
1263
1264 pEntry += kCatalogEntrySize;
1265 }
1266
1267 return kDIErrNone;
1268 }
1269
1270 /*
1271 * Read some fields from the disk Volume Table of Contents.
1272 */
1273 static DIError ReadVTOC(void)
1274 {
1275 DIError dierr;
1276
1277 dierr = ReadTrackSector(kVTOCTrack, kVTOCSector, fVTOC);
1278 if (dierr != kDIErrNone)
1279 goto bail;
1280
1281 fFirstCatTrack = fVTOC[0x01];
1282 fFirstCatSector = fVTOC[0x02];
1283 fVTOCVolumeNumber = fVTOC[0x06];
1284 fVTOCNumTracks = fVTOC[0x34];
1285 fVTOCNumSectors = fVTOC[0x35];
1286
1287 if (fFirstCatTrack >= kNumTracks)
1288 return kDIErrBadDiskImage;
1289 if (fFirstCatSector >= kNumSectPerTrack)
1290 return kDIErrBadDiskImage;
1291
1292 if (fVTOCNumTracks != kNumTracks) {
1293 debug_print(" DOS33 warning: VTOC numtracks %d vs %d\n",
1294 fVTOCNumTracks, kNumTracks);
1295 }
1296 if (fVTOCNumSectors != kNumSectPerTrack) {
1297 debug_print(" DOS33 warning: VTOC numsect %d vs %d\n",
1298 fVTOCNumSectors, kNumSectPerTrack);
1299 }
1300
1301 bail:
1302 return dierr;
1303 }
1304
1305 /*
1306 * Read the disk's catalog.
1307 *
1308 * NOTE: supposedly DOS stops reading the catalog track when it finds the
1309 * first entry with a 00 byte, which is why deleted files use ff. If so,
1310 * it *might* make sense to mimic this behavior, though on a health disk
1311 * we shouldn't be finding garbage anyway.
1312 *
1313 * Fills out "fCatalogSectors" as it works.
1314 */
1315 static DIError ReadCatalog(void)
1316 {
1317 DIError dierr = kDIErrNone;
1318 uint8_t sctBuf[kSectorSize];
1319 int catTrack, catSect;
1320 int iterations;
1321
1322 catTrack = fFirstCatTrack;
1323 catSect = fFirstCatSector;
1324 iterations = 0;
1325
1326 memset(fCatalogSectors, 0, sizeof(fCatalogSectors));
1327
1328 while (catTrack != 0 && catSect != 0 && iterations < kMaxCatalogSectors) {
1329 dierr = ReadTrackSector(catTrack, catSect, sctBuf);
1330 if (dierr != kDIErrNone)
1331 goto bail;
1332
1333 /*
1334 * Watch for flaws that the DOS detector allows.
1335 */
1336 if (catTrack == sctBuf[0x01] && catSect == sctBuf[0x02]) {
1337 debug_print(" DOS detected self-reference on cat (%d,%d)\n",
1338 catTrack, catSect);
1339 break;
1340 }
1341
1342 /*
1343 * Check the next track/sector in the chain. If the pointer is
1344 * broken, there's a very good chance that this isn't really a
1345 * catalog sector, so we want to bail out now.
1346 */
1347 if (sctBuf[0x01] >= kNumTracks || sctBuf[0x02] >= kNumSectPerTrack) {
1348 debug_print(" DOS bailing out early on catalog read due to funky T/S\n");
1349 break;
1350 }
1351
1352 dierr = ProcessCatalogSector(catTrack, catSect, sctBuf);
1353 if (dierr != kDIErrNone)
1354 goto bail;
1355
1356 fCatalogSectors[iterations].track = catTrack;
1357 fCatalogSectors[iterations].sector = catSect;
1358
1359 catTrack = sctBuf[0x01];
1360 catSect = sctBuf[0x02];
1361
1362 iterations++; // watch for infinite loops
1363 }
1364 if (iterations >= kMaxCatalogSectors) {
1365 dierr = kDIErrDirectoryLoop;
1366 goto bail;
1367 }
1368
1369 bail:
1370 return dierr;
1371 }
1372
1373 static A2FileDOS *find_file_named(char *name)
1374 {
1375 debug_print("find_file_named: \"%s\"\n", name);
1376 A2FileDOS *file = firstfile;
1377 while (file != NULL) {
1378 debug_print("Comparing to file named: \"%s\"\n", (char *)file->fFileName);
1379 if (strcmp(name, (char *)file->fFileName) == 0)
1380 break;
1381 file = file->next;
1382 }
1383 return file;
1384 }
1385
1386 static A2FileDOS *find_SAGA_database(void)
1387 {
1388 A2FileDOS *file = firstfile;
1389 while (file != NULL) {
1390 char *name = (char *)file->fFileName;
1391 debug_print("Comparing to file named: \"%s\"\n", name);
1392 if (strcmp("DATABASE", name) == 0)
1393 break;
1394 if (strcmp("SORCEROR OF CLAYMORGUE CASTLE", name) == 0)
1395 break;
1396 if (strcmp("THE INCREDIBLE HULK", name) == 0)
1397 break;
1398 if (name[0] == 'A' && name[2] == '.' && name[3] == 'D' && name[4] == 'A' && name[5] == 'T') {
1399 break; //A(adventure number).DAT
1400 }
1401 file = file->next;
1402 }
1403 return file;
1404 }
1405
1406 uint8_t *ReadApple2DOSFile(uint8_t *data, size_t *len, uint8_t **invimg, size_t *invimglen, uint8_t **m2)
1407 {
1408 rawdata = data;
1409 rawdatalen = *len;
1410
1411 uint8_t *buf = NULL;
1412 ReadVTOC();
1413 ReadCatalog();
1414 A2FileDOS *file = find_SAGA_database();
1415 if (file) {
1416 Open(file);
1417 buf = MemAlloc(file->fLengthInSectors * kSectorSize);
1418 size_t actual;
1419 Read(file, buf, (file->fLengthInSectors - 1) * kSectorSize, &actual);
1420 *len = actual;
1421 }
1422 /* Many games have the inventory image on the boot disk (and the rest of the images on the other disk) */
1423 file = find_file_named("PAK.INVEN");
1424 if (!file) {
1425 file = find_file_named("PAC.INVEN");
1426 }
1427 if (file) {
1428 Open(file);
1429 uint8_t *inventemp = MemAlloc(file->fLengthInSectors * kSectorSize);
1430 debug_print("inventemp is size %d\n", file->fLengthInSectors * kSectorSize);
1431 Read(file, inventemp, (file->fLengthInSectors - 1) * kSectorSize, invimglen);
1432 debug_print("*invimglen is %zu\n", *invimglen);
1433 debug_print("*invimglen - 4 is %zu\n", *invimglen);
1434 *invimg = MemAlloc(*invimglen);
1435 if (*invimglen < 4 || *invimglen > 100000) {
1436 *invimglen = 0;
1437 *invimg = NULL;
1438 } else {
1439 memcpy(*invimg, inventemp + 4, *invimglen - 4);
1440 }
1441 free(inventemp);
1442 }
1443
1444 /* Image unscrambling tables are usually found somewhere in a file named M2 (As in memory part 2?) */
1445 file = find_file_named("M2");
1446 if (file) {
1447 Open(file);
1448 uint8_t *m2temp = MemAlloc(file->fLengthInSectors * kSectorSize);
1449 size_t m2len;
1450 Read(file, m2temp, (file->fLengthInSectors - 1) * kSectorSize, &m2len);
1451
1452 if (m2len > 0x1747 + 0x180 && strncmp((char *)(m2temp + 0x172C), "COPYRIGHT 1983 NORMAN L. SAILER", 31) == 0) {
1453 *m2 = MemAlloc(0x182);
1454 memcpy(*m2, m2temp + 0x174B, 0x182);
1455 }
1456 free(m2temp);
1457 }
1458
1459 return buf;
1460 }