Previous 15994 Revisions Next

r1340 Monday 26th November, 2007 at 21:33:59 UTC by Dirk Best
[IMGTOOL] Moved modules to their own directory, cleaned makefile up a bit.
[ROOT]
[src/mess/tools/imgtool]cococas.c concept.c crt.c cybiko.c d64.c d64.h fat.c fmsx_cas.c imgtool.mak lynx.c mac.c macbin.c macutil.c macutil.h msx_dsk.c nccard.c os9.c pc_flop.c pc_hard.c prodos.c rom16.c rsdos.c svi_cas.c t64.c thomson.c ti85.c ti99.c ti990hd.c vmsx_gm2.c vmsx_tap.c vzdos.c xsa.c
[src/mess/tools/imgtool/modules]cococas.c* concept.c* crt.c* cybiko.c* d64.c* d64.h* fat.c* fmsx_cas.c* lynx.c* mac.c* macbin.c* macutil.c* macutil.h* msx_dsk.c* nccard.c* os9.c* pc_flop.c* pc_hard.c* prodos.c* rom16.c* rsdos.c* svi_cas.c* t64.c* thomson.c* ti85.c* ti99.c* ti990hd.c* vmsx_gm2.c* vmsx_tap.c* vzdos.c* xsa.c*
[src/osd]winui

src/mess/tools/imgtool/ti99.c
r1339r1340
1/*
2   Handlers for ti99 disk images
3
4   We support the following types of image:
5   * floppy disks ("DSK format") in v9t9, pc99 and old mess image format
6   * hard disks ("WIN format") in MAME harddisk format (256-byte sectors only,
7     i.e. no SCSI)
8   Files are extracted in TIFILES format.  There is a compile-time option to
9   extract text files in flat format instead, but I need to re-implement it
10   properly (using filters comes to mind).
11
12   Raphael Nabet, 2002-2004
13
14   TODO:
15   - finish and test hd support ***test sibling FDR support***
16   - check allocation bitmap against corruption when an image is opened
17*/
18
19#include <limits.h>
20#include <stdio.h>
21#include <string.h>
22#include <stdlib.h>
23#include <time.h>
24#include <assert.h>
25#include "osdepend.h"
26#include "imgtoolx.h"
27#include "harddisk.h"
28#include "imghd.h"
29
30/*
31   Concepts shared by both disk structures:
32   ----------------------------------------
33
34   In both formats, the entire disk surface is split into physical records,
35   each 256-byte-long.  For best efficiency, the sector size is usually 256
36   bytes so that one sector is equivalent to a physical record (this is true
37   with floppies and HFDC hard disks).  If the sector size is not 256 bytes
38   (e.g. 512 bytes with SCSI hard disks, possibly 128 bytes on a TI-99
39   simulator running on TI-990), sectors are grouped or split to form 256-byte
40   physical records.  Physical records are numbered from 0, with the first
41   starting on sector 0 track 0.  To avoid confusion with physical records in
42   files, such physical records will be called "absolute physical records",
43   abbreviated as "absolute physrecs" or "aphysrecs".
44
45   Disk space is allocated in units referred to as AUs.  Each AU represents an
46   integral number of 256-byte physical records.  The number of physrecs per
47   AU varies depending on the disk format and size.  AUs are numbered from 0,
48   with the first starting with absolute physrec 0.
49
50   Absolute physrec 0 contains a 256-byte record with volume information,
51   which is called "Volume Information Block", abbreviated as "vib".
52
53   To keep track of which areas on the disk are allocated and which are free,
54   disk managers maintain a bit map of allocated AUs (called "allocation
55   bitmap", abbreviated as "abm").  Each bit in the allocation bitmap
56   represents an AU: if a bit is 0, the AU is free; if a bit is 1, the AU is
57   allocated (or possibly bad if the disk manager can track bad sectors).
58   Where on the disk the abm is located depends on the disk structure (see
59   structure-specific description for details).
60
61   Files are implemented as a succession of 256-byte physical records.  To
62   avoid confusion with absolute physical records, these physical records will
63   be called "file physical records", abbreviated as "file physrecs" or
64   "fphysrecs".
65
66   Programs do normally not access file physical records directly.  They may
67   call high-level file routines that enable to create either fixed-lenght
68   logical records of any size from 1 through 255, or variable-lenght records
69   of any size from 0 through 254: logical records are grouped by file
70   managers into 256-byte physical records.  Some disk managers (HFDC and
71   SCSI) allow programs to create fixed-lenght records larger than 255 bytes,
72   too, but few programs use this possibility.  Additionally, program files
73   can be created: program files do not implement any logical record, and can
74   be seen as a flat byte stream, not unlike files under MSDOS, UNIX and the C
75   standard library.  (Unfortunately, the API for program files lacks
76   flexibility, and most programs that need to process a flat byte stream
77   will use fixed-size records of 128 bytes.)
78
79      Fixed-length records (reclen < 256) are grouped like this:
80           fphysrec 0        fphysrec 1
81         _______________   _______________
82         |R0 |R1 |R2 |X|   |R3 |R4 |R5 |X|
83         ---------------   ---------------
84                     \_/               \_/
85                    unused            unused
86               (size < reclen)   (size < reclen)
87
88      Fixed-length records (reclen > 256) are grouped like this:
89           fphysrec 0         fphysrec 1         fphysrec 2          fphysrec 3      ...
90         _________________  _________________  _________________   _________________
91         |  R0 (#0-255)  |  | R0 (#256-511) |  |R0 (#512-end)|X|   |  R1 (#0-255)  |   ...
92         -----------------  -----------------  -----------------   -----------------
93                                                             \_/
94                                                            unused
95
96      Variable lenght records are grouped like this:
97                          fphysrec 0:
98         byte:
99                 ------------------------------
100               0 |l0 = lenght of record 0 data|
101                 |----------------------------|
102               1 |                            |
103                 |                            |
104               : |       record 0 data        |
105                 |                            |
106              l0 |                            |
107                 |----------------------------|
108            l0+1 |l1 = lenght of record 1 data|
109                 |----------------------------|
110            l0+2 |                            |
111                 |                            |
112               : |       record 1 data        |
113                 |                            |
114         l0+l1+1 |                            |
115                 |----------------------------|
116               : :                            :
117               : :                            :
118                 |----------------------------|
119               n |lm = lenght of record m data|
120                 |----------------------------|
121             n+1 |                            |
122                 |                            |
123               : |       record m data        |
124                 |                            |
125            n+lm |                            |
126                 |----------------------------|
127          n+lm+1 |>ff: EOR mark               |
128                 |----------------------------|
129          n+lm+2 |                            |
130                 |                            |
131               : |           unused           |
132               : |(we should have size < lm+1)|
133                 |                            |
134             255 |                            |
135                 ------------------------------
136
137                          fphysrec 1:
138         byte:
139                 ------------------------------
140               0 |lm+1=lenght of record 0 data|
141                 |----------------------------|
142               1 |                            |
143                 |                            |
144               : |      record m+1 data       |
145                 |                            |
146            lm+1 |                            |
147                 |----------------------------|
148               : :                            :
149               : :                            :
150
151         I think the EOR mark is not required if all 256 bytes of a physical
152         record are used by logical records.
153
154
155   All files are associated with a "file descriptor record" ("fdr") that holds
156   file information (name, format, length) and points to the data AUs. The WIN
157   disk structure also supports sibling FDRs, in case a file is so fragmented
158   that all the data pointers cannot fit in one FDR; the DSK disk structure
159   does not implement any such feature, and you may be unable to append data
160   to an existing file if it is too fragmented, even though the disk is not
161   full.
162
163
164   DSK disk structure:
165   -------------------
166
167   The DSK disk structure is used for floppy disks, and a few RAMDISKs as
168   well.  It supports 1600 AUs and 16 MBytes at most (the 16 MByte value is a
169   theorical maximum, as I doubt anyone has ever created so big a DSK volume).
170
171   The disk sector size is always 256 bytes (the only potential exceptions are
172   the SCSI floppy disk units and the TI-99 simulator on TI-990, but I don't
173   know anything about either).
174
175   For some reason, the number of physrecs per AU is always a power of 2.
176   Originally, AUs always were one physical record each.  However, since the
177   allocation bitmap cannot support more than 1600 AUs, disks larger than
178   400kbytes need to have several physical records per AU.  Note that
179   relatively few disk controllers implement AUs that span multiple physical
180   records (IIRC, these are Myarc's HFDC, SCSI DSR with floppy disk interface,
181   and some upgraded Myarc and Corcomp DD floppy controllers).
182
183   The allocation bitmap is located in the VIB.  It is 200 bytes long, and
184   supports 1600 AUs at most.
185
186   Directories are implemented with a "File Descriptor Index Record" (FDIR)
187   for each directory.  The FDIR is array of 0 through 128 words, containing
188   the aphysrec address of each fdr in the directory, sorted by ascending file
189   name, terminated with a 0.  Note that, while we should be prepared to read
190   images images with 128 entries, I think (not 100% sure) that we should
191   write no more than 127 for compatibility with some existing disk managers.
192
193   Originally, the DSK structure only supported one directory level (i.e. the
194   root directory level).  The FDIR record for the root directory is always
195   located in aphysrec 1.  Moreover, Myarc extended the DSK structure to
196   support up to 3 subdirectories in the root directory (note that there is no
197   support for more subdirs, or for subdirs located in subdirs).  To do so,
198   they used an unused field of the VIB to hold the 10-char name of each
199   directory and the aphysrec address of the associated FDIR record.
200
201   aphysrec 0: Volume Information Block (VIB): see below
202   aphysrec 1: FDIR for root directory
203   Remaining AUs are used for fdr and data (and subdirectory FDIR if
204   applicable).  There is one FDIR record per directory; the FDIR points to
205   the FDR for each file in the directory.  The FDR (File Descriptor Record)
206   contains the file information (name, format, lenght, pointers to data
207   physrecs/AUs, etc).
208
209
210   WIN disk structure:
211   -------------------
212
213   The WIN disk structure is used for hard disks.  It supports 65535 AUs and
214   256 MBytes at most.
215
216   The disk sector size is 256 bytes on HFDC, 512 bytes on SCSI.  512-byte
217   sectors are split into 256-byte physical records.
218
219   We may have from 1 through 16 physrecs per AUs.  Since we cannot have more
220   than 65535 AUs, we need to have several physical records per AU in disks
221   larger than 16 Mbytes.
222
223   Contrary to the DSK disk structure, the WIN disk structure supports
224   hierarchic subdirectories, with a limit of 114 subdirectories and 127 files
225   per directory.  Each directory is associated with both a "Directory
226   Descriptor Record" (DDR) and a "File Descriptor Index Record" (FDIR).  The
227   only exception is the root directory, which uses the VIB instead of a DDR
228   (the VIB includes all the important fields of the DDR).  The DDR contains
229   some directory info (name, number of files and subdirectories directly
230   enclosed in the directory, AU address of the FDIR of the parent directory,
231   etc), the AU address of the associated FDIR, and the AU address of the DDR
232   of up to 114 subdirectories, sorted by ascending directory name.  The WIN
233   FDIR is similar to, yet different from, the DSK FDIR: it contains up to 127
234   (vs. 128) AU address (vs. aphysrec address) of each fdr in the directory,
235   sorted by ascending file name.  Additionally, it includes the AU address of
236   the associated DDR.
237
238   When a file has more than 54 data fragments, the disk manager creates
239   sibling FDRs that hold additional fragments.  (Sibling FDRs are called
240   offspring FDRs in most existing documentation, but I prefer "sibling FDRs"
241   as "offspring FDRs" wrongly suggests a directory-like hierarchy.
242   Incidentally, I cannot really figure out why they chose to duplicate the
243   FDR rather than create a file extension record, but there must be a
244   reason.)  Note that sibling FDRs usually fill unused physrecs in the AU
245   allocated for the eldest FDR, and a new AU is allocated for new sibling
246   FDRs only when the first AU is full.
247
248   aphysrec 0: Volume Information Block (VIB): see below
249   aphysrec 1-n (where n = 1+SUP(number_of_AUs/2048)): Volume bitmap
250   Remaining AUs are used for ddr, fdir, fdr and data.
251*/
252
253/* Since string length is encoded with a byte, the maximum length of a string
254is 255.  Since we need to add a device name (1 char minimum, typically 4 chars)
255and a '.' separator, we chose a practical value of 250 (though few applications
256will accept paths of such lenght). */
257#define MAX_PATH_LEN 253
258#define MAX_SAFE_PATH_LEN 250
259
260#define MAX_DIR_LEVEL 125   /* We need to put a recursion limit to avoid endless recursion hazard */
261
262
263#if 0
264#pragma mark MISCELLANEOUS UTILITIES
265#endif
266
267/*
268   Miscellaneous utilities that are used to handle TI data types
269*/
270
271typedef struct UINT16BE
272{
273   UINT8 bytes[2];
274} UINT16BE;
275
276typedef struct UINT16LE
277{
278   UINT8 bytes[2];
279} UINT16LE;
280
281INLINE UINT16 get_UINT16BE(UINT16BE word)
282{
283   return (word.bytes[0] << 8) | word.bytes[1];
284}
285
286INLINE void set_UINT16BE(UINT16BE *word, UINT16 data)
287{
288   word->bytes[0] = (data >> 8) & 0xff;
289   word->bytes[1] = data & 0xff;
290}
291
292INLINE UINT16 get_UINT16LE(UINT16LE word)
293{
294   return word.bytes[0] | (word.bytes[1] << 8);
295}
296
297INLINE void set_UINT16LE(UINT16LE *word, UINT16 data)
298{
299   word->bytes[0] = data & 0xff;
300   word->bytes[1] = (data >> 8) & 0xff;
301}
302
303/*
304   Convert a C string to a 10-character file name (padded with spaces if necessary)
305
306   dst (O): destination 10-character array
307   src (I): source C string
308*/
309static void str_to_fname(char dst[10], const char *src)
310{
311   int i;
312
313
314   i = 0;
315
316   /* copy 10 characters at most */
317   if (src)
318      while ((i<10) && (src[i]!='\0'))
319      {
320         dst[i] = src[i];
321         i++;
322      }
323
324   /* pad with spaces */
325   while (i<10)
326   {
327      dst[i] = ' ';
328      i++;
329   }
330}
331
332/*
333   Convert a 10-character file name to a C string (removing trailing spaces if necessary)
334
335   dst (O): destination C string
336   src (I): source 10-character array
337   n (I): lenght of dst buffer (string may be truncated if less than 11)
338*/
339static void fname_to_str(char *dst, const char src[10], int n)
340{
341   int i;
342   int last_nonspace;
343
344
345   /* copy 10 characters at most */
346   if (--n > 10)
347      n = 10;
348
349   /* copy filename */
350   i = 0;
351   last_nonspace = -1;
352
353   while (i<n)
354   {
355      dst[i] = src[i];
356      if (src[i] != ' ')
357         last_nonspace = i;
358      i++;
359   }
360
361   /* terminate with '\0' */
362   dst[last_nonspace+1] = '\0';
363}
364
365/*
366   Check a 10-character file name.
367
368   filename (I): 10-character array with file name
369
370   Return non-zero if the file name is invalid.
371*/
372static int check_fname(const char filename[10])
373{
374   int i;
375   int space_found_flag;
376
377
378   /* check and copy file name */
379   space_found_flag = FALSE;
380   for (i=0; i<10; i++)
381   {
382      switch (filename[i])
383      {
384      case '.':
385      case '\0':
386         /* illegal characters */
387         return 1;
388      case ' ':
389         /* illegal in a file name, but file names shorter than 10
390         characters are padded with spaces */
391         space_found_flag = TRUE;
392         break;
393      default:
394         /* all other characters are legal (though non-ASCII characters,
395         control characters and even lower-case characters are not
396         recommended) */
397         if (space_found_flag)
398            return 1;
399         break;
400      }
401   }
402
403   return 0;
404}
405
406/*
407   Check a file path.
408
409   fpath (I): C string with file path
410
411   Return non-zero if the file path is invalid.
412*/
413static int check_fpath(const char *fpath)
414{
415   const char *element_start, *element_end;
416   int element_len;
417
418
419   /* first check that the path is not too long and that there is no space
420   character */
421   if ((strlen(fpath) > MAX_PATH_LEN) || strchr(fpath, ' '))
422      return 1;
423
424   /* check that each path element has an acceptable lenght */
425   element_start = fpath;
426   do
427   {
428      /* find next path element */
429      element_end = strchr(element_start, '.');
430      element_len = element_end ? (element_end - element_start) : strlen(element_start);
431      if ((element_len > 10) || (element_len == 0))
432         return 1;
433
434      /* iterate */
435      if (element_end)
436         element_start = element_end+1;
437      else
438         element_start = NULL;
439   }
440   while (element_start);
441
442   return 0;
443}
444
445#if 0
446#pragma mark -
447#pragma mark LEVEL 1 DISK ROUTINES
448#endif
449
450/*
451   Level 1 deals with accessing the disk hardware (in our case, the raw disk
452   image).
453
454   Higher level routines will only know the disk as a succession of
455   256-byte-long physical records addressed by a linear address.
456*/
457
458/*
459   Disk geometry
460*/
461typedef struct ti99_geometry
462{
463   int secspertrack;
464   int cylinders;
465   int heads;
466} ti99_geometry;
467
468/*
469   Physical sector address
470*/
471typedef struct ti99_sector_address
472{
473   int sector;
474   int cylinder;
475   int side;
476} ti99_sector_address;
477
478/*
479   Time stamp (used in fdr, and WIN VIB/DDR)
480*/
481typedef struct ti99_date_time
482{
483   UINT8 time_MSB, time_LSB;/* 0-4: hour, 5-10: minutes, 11-15: seconds/2 */
484   UINT8 date_MSB, date_LSB;/* 0-6: year, 7-10: month, 11-15: day */
485} ti99_date_time;
486
487/*
488   Subdirectory descriptor (HFDC only)
489
490   The HFDC supports up to 3 subdirectories.
491*/
492typedef struct dsk_subdir
493{
494   char name[10];         /* subdirectory name (10 characters, pad with spaces) */
495   UINT16BE fdir_aphysrec;   /* aphysrec address of fdir record for this subdirectory */
496} dsk_subdir;
497
498/*
499   DSK VIB record
500
501   Most fields in this record are only revelant to level 2 routines, but level
502   1 routines need the disk geometry information extracted from the VIB.
503*/
504typedef struct dsk_vib
505{
506   char name[10];         /* disk volume name (10 characters, pad with spaces) */
507   UINT16BE totphysrecs;   /* total number of physrecs on disk (usually 360, */
508                        /* 720, 640, 1280 or 1440).  (TI originally */
509                        /* said it should be the total number of AUs, */
510                        /* but, in practice, DSRs that supports disks */
511                        /* over 400kbytes (e.g. HFDC) write the total */
512                        /* number of physrecs.) */
513   UINT8 secspertrack;      /* sectors per track (usually 9 (FM SD), */
514                        /* 16 or 18 (MFM DD), or 36 (MFM HD) */
515   UINT8 id[3];         /* 'DSK' */
516   UINT8 protection;      /* 'P' if disk is protected, ' ' otherwise. */
517   UINT8 cylinders;      /* tracks per side (usually 40) */
518   UINT8 heads;         /* sides (1 or 2) */
519   UINT8 density;         /* density: 1 (FM SD), 2 (MFM DD), or 3 (MFM HD) */
520   dsk_subdir subdir[3];   /* descriptor for up to 3 subdirectories (HFDC only) */
521                        /* reserved by TI */
522   UINT8 abm[200];         /* allocation bitmap: there is one bit per AU. */
523                        /* A binary 1 in a bit position indicates that */
524                        /* the allocation unit associated with that */
525                        /* bit has been allocated. */
526                        /* Bits corresponding to system reserved AUs, */
527                        /* non-existant AUs, and bad AUs, are set to one, too. */
528                        /* (AU 0 is associated to LSBit of byte 0, */
529                        /* AU 7 to MSBit of byte 0, AU 8 to LSBit */
530                        /* of byte 1, etc.) */
531} dsk_vib;
532
533typedef enum
534{
535   if_mess,
536   if_v9t9,
537   if_pc99_fm,
538   if_pc99_mfm,
539   if_harddisk
540} ti99_img_format;
541
542/*
543   level-1 disk image descriptor
544*/
545typedef struct ti99_lvl1_imgref
546{
547   ti99_img_format img_format;   /* tells the image format */
548   imgtool_stream *file_handle;      /* imgtool file handle */
549   struct mess_hard_disk_file harddisk_handle;      /* MAME harddisk handle (harddisk format) */
550   ti99_geometry geometry;      /* geometry */
551   unsigned pc99_track_len;      /* unformatted track lenght (pc99 format) */
552   UINT32 *pc99_data_offset_array;   /* offset for each sector (pc99 format) */
553} ti99_lvl1_imgref;
554
555/*
556   calculate CRC for data address marks or sector data
557
558   crc (I/O): current CRC value to be updated (initialize to 0xffff before
559      calling this function for the first time)
560   value: new byte of data to update the CRC with
561*/
562static void calc_crc(UINT16 *crc, UINT8 value)
563{
564   UINT8 l, h;
565
566   l = value ^ (*crc >> 8);
567   *crc = (*crc & 0xff) | (l << 8);
568   l >>= 4;
569   l ^= (*crc >> 8);
570   *crc <<= 8;
571   *crc = (*crc & 0xff00) | l;
572   l = (l << 4) | (l >> 4);
573   h = l;
574   l = (l << 2) | (l >> 6);
575   l &= 0x1f;
576   *crc = *crc ^ (l << 8);
577   l = h & 0xf0;
578   *crc = *crc ^ (l << 8);
579   l = (h << 1) | (h >> 7);
580   l &= 0xe0;
581   *crc = *crc ^ l;
582}
583
584/*
585   Parse a PC99 disk image
586
587   file_handle (I/O): imgtool file handle
588   fm_format (I): if true, the image is in FM format, otherwise it is in MFM
589      format
590   pass (I): 0 for first pass, 1 for second pass
591   vib (O): buffer where the vib should be stored (first pass)
592   geometry (O): disk image geometry (second pass)
593   data_offset_array (O): array of data offset to generate (second pass)
594   out_track_len (O): track lenght is returned there
595
596   Return imgtool error code
597*/
598#define MAX_TRACK_LEN 6872
599#define DATA_OFFSET_NONE 0xffffffff
600static int parse_pc99_image(imgtool_stream *file_handle, int fm_format, int pass, dsk_vib *vib, const ti99_geometry *geometry, UINT32 *data_offset_array, unsigned *out_track_len)
601{
602   int track_len, num_tracks;   /* lenght of a track in bytes, and number of tracks */
603   int phys_track;
604   int expected_cylinder, expected_head;
605   int track_start_pos, track_pos;
606   UINT8 c;
607   UINT8 cylinder, head, sector;
608   int seclen;
609   UINT8 crc1, crc2;
610   UINT16 crc;
611   long data_offset;
612   UINT8 track_buf[MAX_TRACK_LEN];
613   int i;
614
615   if (fm_format)
616      track_len = 3253;
617   else
618      track_len = 6872;
619
620   if (out_track_len)
621      *out_track_len = track_len;
622
623   if (stream_size(file_handle) % track_len)
624      return IMGTOOLERR_CORRUPTIMAGE;
625
626   num_tracks = stream_size(file_handle) / track_len;
627   if (num_tracks <= 0)
628      return IMGTOOLERR_CORRUPTIMAGE;
629
630   /* we only support 40-track-per-side images */
631   if ((num_tracks != 40) && (num_tracks != 80))
632      return IMGTOOLERR_UNIMPLEMENTED;
633
634   if (pass == 1)
635   {
636      /* initialize offset map */
637      for (head = 0; head < geometry->heads; head++)
638         for (cylinder = 0; cylinder < geometry->cylinders; cylinder++)
639            for (sector = 0; sector < geometry->secspertrack; sector++)
640               data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] = DATA_OFFSET_NONE;
641   }
642   /* rewind to start of file */
643   stream_seek(file_handle, 0, SEEK_SET);
644
645   /* pass 0 only looks for vib in track 0; pass 1 scans every track */
646   for (phys_track=0; phys_track < ((pass == 1) ? num_tracks : 1); phys_track++)
647   {
648      if (stream_read(file_handle, track_buf, track_len) != track_len)
649         return IMGTOOLERR_READERROR;
650
651      /* we only support 40-track-per-side images */
652      expected_cylinder = phys_track % 40;
653      expected_head = phys_track / 40;
654
655      track_start_pos = 0;
656
657      while (track_start_pos < track_len)
658      {
659         if (fm_format)
660         {
661            do
662            {
663               c = track_buf[track_start_pos];
664               track_start_pos++;
665            } while ((c != 0xfe) && (track_start_pos < track_len));
666
667            if (c != 0xfe)
668               break;
669
670            track_pos = track_start_pos;
671
672            crc = 0xffff;
673            calc_crc(& crc, c);
674         }
675         else
676         {
677            do
678            {
679               c = track_buf[track_start_pos];
680               track_start_pos++;
681            } while ((c != 0xa1) && (track_start_pos < track_len));
682
683            if (c != 0xa1)
684               break;
685
686            track_pos = track_start_pos;
687
688            c = track_buf[track_pos];
689            track_pos++;
690            if (track_pos == track_len)
691               track_pos = 0;
692
693            if (c != 0xa1)
694               continue;
695
696            c = track_buf[track_pos];
697            track_pos++;
698            if (track_pos == track_len)
699               track_pos = 0;
700
701            if (c != 0xa1)
702               continue;
703
704            crc = 0xffff;
705            calc_crc(& crc, c);
706
707            c = track_buf[track_pos];
708            track_pos++;
709            if (track_pos == track_len)
710               track_pos = 0;
711
712            if (c != 0xfe)
713               continue;
714         }
715
716         c = track_buf[track_pos];
717         track_pos++;
718         if (track_pos == track_len)
719            track_pos = 0;
720
721         cylinder = c;
722         calc_crc(& crc, c);
723
724         c = track_buf[track_pos];
725         track_pos++;
726         if (track_pos == track_len)
727            track_pos = 0;
728
729         head = c;
730         calc_crc(& crc, c);
731
732         c = track_buf[track_pos];
733         track_pos++;
734         if (track_pos == track_len)
735            track_pos = 0;
736
737         sector = c;
738         calc_crc(& crc, c);
739
740         c = track_buf[track_pos];
741         track_pos++;
742         if (track_pos == track_len)
743            track_pos = 0;
744
745         seclen = 128 << c;
746         calc_crc(& crc, c);
747
748         c = track_buf[track_pos];
749         track_pos++;
750         if (track_pos == track_len)
751            track_pos = 0;
752
753         crc1 = c;
754         calc_crc(& crc, c);
755
756         c = track_buf[track_pos];
757         track_pos++;
758         if (track_pos == track_len)
759            track_pos = 0;
760
761         crc2 = c;
762         calc_crc(& crc, c);
763
764         /* CRC seems to be completely hosed */
765         /*if (crc)
766            printf("aargh!");*/
767         if ((seclen != 256) || (crc1 != 0xf7) || (crc2 != 0xf7)
768               || (cylinder != expected_cylinder) || (head != expected_head)
769               || ((pass == 1) && ((cylinder >= geometry->cylinders)
770                              || (head >= geometry->heads)
771                              || (sector >= geometry->secspertrack))))
772            continue;
773
774         c = track_buf[track_pos];
775         track_pos++;
776         if (track_pos == track_len)
777            track_pos = 0;
778
779         while (c == (fm_format ? 0xff : 0x4e))
780         {
781            c = track_buf[track_pos];
782            track_pos++;
783            if (track_pos == track_len)
784               track_pos = 0;
785         }
786
787         while (c == 0x00)
788         {
789            c = track_buf[track_pos];
790            track_pos++;
791            if (track_pos == track_len)
792               track_pos = 0;
793         }
794
795         if (fm_format)
796         {
797            if (c != 0xfb)
798               continue;
799
800            crc = 0xffff;
801            calc_crc(& crc, c);
802         }
803         else
804         {
805            if (c != 0xa1)
806               continue;
807
808            c = track_buf[track_pos];
809            track_pos++;
810            if (track_pos == track_len)
811               track_pos = 0;
812
813            if (c != 0xa1)
814               continue;
815
816            c = track_buf[track_pos];
817            track_pos++;
818            if (track_pos == track_len)
819               track_pos = 0;
820
821            if (c != 0xa1)
822               continue;
823
824            crc = 0xffff;
825            calc_crc(& crc, c);
826
827            c = track_buf[track_pos];
828            track_pos++;
829            if (track_pos == track_len)
830               track_pos = 0;
831
832            if (c != 0xfb)
833               continue;
834         }
835         data_offset = track_pos;
836         for (i=0; i<seclen; i++)
837         {
838            c = track_buf[track_pos];
839            track_pos++;
840            if (track_pos == track_len)
841               track_pos = 0;
842
843            calc_crc(& crc, c);
844         }
845
846         c = track_buf[track_pos];
847         track_pos++;
848         if (track_pos == track_len)
849            track_pos = 0;
850
851         crc1 = c;
852         calc_crc(& crc, c);
853
854         c = track_buf[track_pos];
855         track_pos++;
856         if (track_pos == track_len)
857            track_pos = 0;
858
859         crc2 = c;
860         calc_crc(& crc, c);
861
862         /* CRC seems to be completely hosed */
863         /*if (crc)
864            printf("aargh!");*/
865         if ((crc1 != 0xf7) || (crc2 != 0xf7))
866            continue;
867
868         switch (pass)
869         {
870         case 0:
871            if ((cylinder == 0) && (head == 0) && (sector == 0))
872            {
873               /* return vib */
874               if ((data_offset + 256) <= track_len)
875                  memcpy(vib, track_buf + data_offset, 256);
876               else
877               {
878                  memcpy((UINT8 *)vib, track_buf + data_offset, track_len-data_offset);
879                  memcpy((UINT8 *)vib + (track_len-data_offset), track_buf, 256-(track_len-data_offset));
880               }
881               return 0;
882            }
883            break;
884
885         case 1:
886            /* set up offset map */
887            if (data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] != DATA_OFFSET_NONE)
888               /* error: duplicate sector */
889               return IMGTOOLERR_CORRUPTIMAGE;
890            data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] = data_offset;
891            break;
892         }
893      }
894   }
895
896   if (pass == 0)
897      return IMGTOOLERR_CORRUPTIMAGE;
898
899   if (pass == 1)
900   {
901      /* check offset map */
902      for (head = 0; head < geometry->heads; head++)
903         for (cylinder = 0; cylinder < geometry->cylinders; cylinder++)
904            for (sector = 0; sector < geometry->secspertrack; sector++)
905               if (data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] == DATA_OFFSET_NONE)
906                  /* error: missing sector */
907                  return IMGTOOLERR_CORRUPTIMAGE;
908   }
909
910   return 0;
911}
912
913
914/*
915   Read the volume information block (aphysrec 0) assuming no geometry
916   information.  (Called when an image is opened to figure out the
917   geometry information.)
918
919   file_handle (I/O): imgtool file handle
920   img_format (I): image format (MESS, V9T9 or PC99)
921   dest (O): pointer to 256-byte destination buffer
922
923   Return imgtool error code
924*/
925static int read_image_vib_no_geometry(imgtool_stream *file_handle, ti99_img_format img_format, dsk_vib *dest)
926{
927   int reply;
928
929   switch (img_format)
930   {
931   case if_mess:
932   case if_v9t9:
933      /* seek to sector */
934      reply = stream_seek(file_handle, 0, SEEK_SET);
935      if (reply)
936         return IMGTOOLERR_READERROR;
937      /* read it */
938      reply = stream_read(file_handle, dest, 256);
939      if (reply != 256)
940         return IMGTOOLERR_READERROR;
941      return 0;
942
943   case if_pc99_fm:
944   case if_pc99_mfm:
945      return parse_pc99_image(file_handle, img_format == if_pc99_fm, 0, dest, NULL, NULL, NULL);
946
947   case if_harddisk:
948      /* not implemented, because we don't need it */
949      break;
950   }
951
952   return IMGTOOLERR_UNIMPLEMENTED;
953}
954
955/*
956   Open a disk image at level 1
957
958   file_handle (I/O): imgtool file handle
959   img_format (I): image format (MESS, V9T9, PC99, or MAME harddisk)
960   l1_img (O): level-1 image handle
961   vib (O): buffer where the vib should be stored (floppy images only)
962
963   Return imgtool error code
964*/
965static imgtoolerr_t open_image_lvl1(imgtool_stream *file_handle, ti99_img_format img_format, ti99_lvl1_imgref *l1_img, dsk_vib *vib)
966{
967   imgtoolerr_t err;
968   int reply;
969   int totphysrecs;
970
971
972   l1_img->img_format = img_format;
973   l1_img->file_handle = file_handle;
974
975   if (img_format == if_harddisk)
976   {
977      const hard_disk_info *info;
978
979      err = imghd_open(file_handle, &l1_img->harddisk_handle);
980      if (err)
981         return err;
982
983      info = imghd_get_header(&l1_img->harddisk_handle);
984      l1_img->geometry.cylinders = info->cylinders;
985      l1_img->geometry.heads = info->heads;
986      l1_img->geometry.secspertrack = info->sectors;
987      if (info->sectorbytes != 256)
988      {
989         imghd_close(&l1_img->harddisk_handle);
990         return IMGTOOLERR_CORRUPTIMAGE;   /* TODO: support 512-byte sectors */
991      }
992
993      /* read vib */
994      /*reply = read_absolute_physrec(l1_img, 0, vib);
995      if (reply)
996         return reply;*/
997   }
998   else
999   {
1000      /* read vib */
1001      reply = read_image_vib_no_geometry(file_handle, img_format, vib);
1002      if (reply)
1003         return reply;
1004
1005      /* extract geometry information */
1006      totphysrecs = get_UINT16BE(vib->totphysrecs);
1007
1008      l1_img->geometry.secspertrack = vib->secspertrack;
1009      if (l1_img->geometry.secspertrack == 0)
1010         /* Some images might be like this, because the original SSSD TI
1011         controller always assumes 9. */
1012         l1_img->geometry.secspertrack = 9;
1013      l1_img->geometry.cylinders = vib->cylinders;
1014      if (l1_img->geometry.cylinders == 0)
1015         /* Some images are like this, because the original SSSD TI
1016         controller always assumes 40. */
1017         l1_img->geometry.cylinders = 40;
1018      l1_img->geometry.heads = vib->heads;
1019      if (l1_img->geometry.heads == 0)
1020         /* Some images are like this, because the original SSSD TI
1021         controller always assumes that tracks beyond 40 are on side 2. */
1022         l1_img->geometry.heads = totphysrecs / (l1_img->geometry.secspertrack * l1_img->geometry.cylinders);
1023
1024      /* check information */
1025      if ((totphysrecs != (l1_img->geometry.secspertrack * l1_img->geometry.cylinders * l1_img->geometry.heads))
1026            || (totphysrecs < 2)
1027            || memcmp(vib->id, "DSK", 3) || (! strchr(" P", vib->id[3]))
1028            || (((img_format == if_mess) || (img_format == if_v9t9))
1029               && (stream_size(file_handle) != totphysrecs*256)))
1030         return IMGTOOLERR_CORRUPTIMAGE;
1031
1032      if ((img_format == if_pc99_fm) || (img_format == if_pc99_mfm))
1033      {
1034         l1_img->pc99_data_offset_array = malloc(sizeof(*l1_img->pc99_data_offset_array)*totphysrecs);
1035         if (! l1_img->pc99_data_offset_array)
1036            return IMGTOOLERR_OUTOFMEMORY;
1037         reply = parse_pc99_image(file_handle, img_format == if_pc99_fm, 1, NULL, & l1_img->geometry, l1_img->pc99_data_offset_array, &l1_img->pc99_track_len);
1038         if (reply)
1039         {
1040            free(l1_img->pc99_data_offset_array);
1041            return reply;
1042         }
1043      }
1044   }
1045
1046   return 0;
1047}
1048
1049/*
1050   Close a disk image at level 1
1051
1052   l1_img (I/O): level-1 image handle
1053
1054   Return imgtool error code
1055*/
1056static void close_image_lvl1(ti99_lvl1_imgref *l1_img)
1057{
1058   if (l1_img->img_format == if_harddisk)
1059   {
1060      imghd_close(&l1_img->harddisk_handle);
1061   }
1062
1063   stream_close(l1_img->file_handle);
1064
1065   if ((l1_img->img_format == if_pc99_fm) || (l1_img->img_format == if_pc99_mfm))
1066      free(l1_img->pc99_data_offset_array);
1067}
1068
1069/*
1070   Convert physical sector address to offset in disk image (old MESS and V9T9
1071   formats only)
1072
1073   l1_img (I/O): level-1 image handle
1074   address (I): physical sector address
1075
1076   Return offset in image
1077*/
1078INLINE int sector_address_to_image_offset(const ti99_lvl1_imgref *l1_img, const ti99_sector_address *address)
1079{
1080   int offset = 0;
1081
1082   switch (l1_img->img_format)
1083   {
1084   case if_mess:
1085      /* old MESS format */
1086      offset = (((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector)*256;
1087      break;
1088
1089   case if_v9t9:
1090      /* V9T9 format */
1091      if (address->side & 1)
1092         /* on side 1, tracks are stored in the reverse order */
1093         offset = (((address->side*l1_img->geometry.cylinders) + (l1_img->geometry.cylinders-1 - address->cylinder))*l1_img->geometry.secspertrack + address->sector)*256;
1094      else
1095         offset = (((address->side*l1_img->geometry.cylinders) + address->cylinder)*l1_img->geometry.secspertrack + address->sector)*256;
1096      break;
1097
1098   case if_pc99_fm:
1099   case if_pc99_mfm:
1100      /* pc99 format */
1101   case if_harddisk:
1102      /* harddisk format */
1103      assert(1);      /* not implemented */
1104      break;
1105   }
1106
1107   return offset;
1108}
1109
1110/*
1111   Read one 256-byte sector from a disk image
1112
1113   l1_img (I/O): level-1 image handle
1114   address (I): physical sector address
1115   dest (O): pointer to 256-byte destination buffer
1116
1117   Return non-zero on error
1118*/
1119static int read_sector(ti99_lvl1_imgref *l1_img, const ti99_sector_address *address, void *dest)
1120{
1121   int reply;
1122   UINT32 track_len, track_offset, sector_offset;
1123
1124   switch (l1_img->img_format)
1125   {
1126   case if_mess:
1127      /* old MESS format */
1128   case if_v9t9:
1129      /* V9T9 format */
1130      /* seek to sector */
1131      reply = stream_seek(l1_img->file_handle, sector_address_to_image_offset(l1_img, address), SEEK_SET);
1132      if (reply)
1133         return 1;
1134      /* read it */
1135      reply = stream_read(l1_img->file_handle, dest, 256);
1136      if (reply != 256)
1137         return 1;
1138      break;
1139
1140   case if_pc99_fm:
1141   case if_pc99_mfm:
1142      /* pc99 format */
1143      track_len = l1_img->pc99_track_len;
1144      track_offset = (address->side*l1_img->geometry.cylinders + address->cylinder)*track_len;
1145      sector_offset = l1_img->pc99_data_offset_array[(address->side*l1_img->geometry.cylinders + address->cylinder)*l1_img->geometry.secspertrack + address->sector];
1146
1147      if ((sector_offset + 256) <= track_len)
1148      {
1149         /* seek to sector */
1150         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1151         if (reply)
1152            return 1;
1153         /* read it */
1154         reply = stream_read(l1_img->file_handle, dest, 256);
1155         if (reply != 256)
1156            return 1;
1157      }
1158      else
1159      {
1160         /* seek to sector */
1161         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1162         if (reply)
1163            return 1;
1164         /* read first chunk (until end of track) */
1165         reply = stream_read(l1_img->file_handle, (UINT8 *)dest, track_len-sector_offset);
1166         if (reply != track_len-sector_offset)
1167            return 1;
1168
1169         /* wrap to start of track */
1170         reply = stream_seek(l1_img->file_handle, track_offset, SEEK_SET);
1171         if (reply)
1172            return 1;
1173         /* read remnant of sector */
1174         reply = stream_read(l1_img->file_handle, (UINT8 *)dest + (track_len-sector_offset), 256-(track_len-sector_offset));
1175         if (reply != 256-(track_len-sector_offset))
1176            return 1;
1177      }
1178      break;
1179
1180   case if_harddisk:
1181      /* not implemented */
1182      assert(1);
1183      /*return imghd_read(l1_img->harddisk_handle, ((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector, 1, dest) != 1;*/
1184      break;
1185   }
1186
1187   return 0;
1188}
1189
1190/*
1191   Write one 256-byte sector to a disk image
1192
1193   l1_img (I/O): level-1 image handle
1194   address (I): physical sector address
1195   src (I): pointer to 256-byte source buffer
1196
1197   Return non-zero on error
1198*/
1199static int write_sector(ti99_lvl1_imgref *l1_img, const ti99_sector_address *address, const void *src)
1200{
1201   int reply;
1202   UINT32 track_len, track_offset, sector_offset;
1203
1204   switch (l1_img->img_format)
1205   {
1206   case if_mess:
1207      /* old MESS format */
1208   case if_v9t9:
1209      /* V9T9 format */
1210      /* seek to sector */
1211      reply = stream_seek(l1_img->file_handle, sector_address_to_image_offset(l1_img, address), SEEK_SET);
1212      if (reply)
1213         return 1;
1214      /* write it */
1215      reply = stream_write(l1_img->file_handle, src, 256);
1216      if (reply != 256)
1217         return 1;
1218      break;
1219
1220   case if_pc99_fm:
1221   case if_pc99_mfm:
1222      /* pc99 format */
1223      track_len = l1_img->pc99_track_len;
1224      track_offset = (address->side*l1_img->geometry.cylinders + address->cylinder)*track_len;
1225      sector_offset = l1_img->pc99_data_offset_array[(address->side*l1_img->geometry.cylinders + address->cylinder)*l1_img->geometry.secspertrack + address->sector];
1226
1227      if ((sector_offset + 256) <= track_len)
1228      {
1229         /* seek to sector */
1230         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1231         if (reply)
1232            return 1;
1233         /* write it */
1234         reply = stream_write(l1_img->file_handle, src, 256);
1235         if (reply != 256)
1236            return 1;
1237      }
1238      else
1239      {
1240         /* seek to sector */
1241         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1242         if (reply)
1243            return 1;
1244         /* write first chunk (until end of track) */
1245         reply = stream_write(l1_img->file_handle, (UINT8 *)src, track_len-sector_offset);
1246         if (reply != track_len-sector_offset)
1247            return 1;
1248
1249         /* wrap to start of track */
1250         reply = stream_seek(l1_img->file_handle, track_offset, SEEK_SET);
1251         if (reply)
1252            return 1;
1253         /* write remnant of sector */
1254         reply = stream_write(l1_img->file_handle, (UINT8 *)src + (track_len-sector_offset), 256-(track_len-sector_offset));
1255         if (reply != 256-(track_len-sector_offset))
1256            return 1;
1257      }
1258      break;
1259
1260   case if_harddisk:
1261      /* not implemented */
1262      assert(1);
1263      /*return imghd_write(l1_img->harddisk_handle, ((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector, 1, src) != 1;*/
1264      break;
1265   }
1266
1267   return 0;
1268}
1269
1270/*
1271   Convert physical record address to sector address (DSK format)
1272
1273   aphysrec (I): absolute physrec address
1274   geometry (I): disk image geometry
1275   address (O): physical sector address
1276*/
1277static void dsk_aphysrec_to_sector_address(int aphysrec, const ti99_geometry *geometry, ti99_sector_address *address)
1278{
1279   address->sector = aphysrec % geometry->secspertrack;
1280   aphysrec /= geometry->secspertrack;
1281   address->cylinder = aphysrec % geometry->cylinders;
1282   address->side = aphysrec / geometry->cylinders;
1283   if (address->side & 1)
1284      /* on side 1, tracks are stored in the reverse order */
1285      address->cylinder = geometry->cylinders-1 - address->cylinder;
1286}
1287
1288/*
1289   Convert physical record address to sector address (WIN format for HFDC)
1290
1291   Note that physical address translation makes sense for HFDC, but not SCSI.
1292
1293   aphysrec (I): absolute physrec address
1294   geometry (I): disk image geometry
1295   address (O): physical sector address
1296*/
1297/*static void win_aphysrec_to_sector_address(int aphysrec, const ti99_geometry *geometry, ti99_sector_address *address)
1298{
1299   address.sector = aphysrec % l1_img->geometry.secspertrack;
1300   aphysrec /= l1_img->geometry.secspertrack;
1301   address.side = aphysrec % l1_img->geometry.heads;
1302   address.cylinder = aphysrec / l1_img->geometry.heads;
1303}*/
1304
1305/*
1306   Read one 256-byte physical record from a disk image
1307
1308   l1_img (I/O): level-1 image handle
1309   aphysrec (I): absolute physrec address
1310   dest (O): pointer to 256-byte destination buffer
1311
1312   Return non-zero on error
1313*/
1314static int read_absolute_physrec(ti99_lvl1_imgref *l1_img, unsigned aphysrec, void *dest)
1315{
1316   ti99_sector_address address;
1317
1318
1319   if (l1_img->img_format == if_harddisk)
1320   {
1321      /*win_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1322
1323      return read_sector(l1_img, & address, dest);*/
1324
1325      return imghd_read(&l1_img->harddisk_handle, aphysrec, dest) != IMGTOOLERR_SUCCESS;
1326   }
1327   else
1328   {
1329      dsk_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1330
1331      return read_sector(l1_img, & address, dest);
1332   }
1333}
1334
1335/*
1336   Write one 256-byte physical record to a disk image
1337
1338   l1_img (I/O): level-1 image handle
1339   aphysrec (I): absolute physrec address
1340   src (I): pointer to 256-byte source buffer
1341
1342   Return non-zero on error
1343*/
1344static int write_absolute_physrec(ti99_lvl1_imgref *l1_img, unsigned aphysrec, const void *src)
1345{
1346   ti99_sector_address address;
1347
1348
1349   if (l1_img->img_format == if_harddisk)
1350   {
1351      /*win_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1352
1353      return write_sector(l1_img, & address, dest);*/
1354
1355      return imghd_write(&l1_img->harddisk_handle, aphysrec, src) != IMGTOOLERR_SUCCESS;
1356   }
1357   else
1358   {
1359      dsk_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1360
1361      return write_sector(l1_img, & address, src);
1362   }
1363}
1364
1365#if 0
1366#pragma mark -
1367#pragma mark LEVEL 2 DISK ROUTINES
1368#endif
1369
1370/*
1371   Level 2 implements files as a succession of 256-byte-long physical records.
1372
1373   Level 2 implements allocation bitmap (and AU), disk catalog, etc.
1374*/
1375
1376/*
1377   WIN VIB/DDR record
1378*/
1379typedef struct win_vib_ddr
1380{
1381   char name[10];         /* disk volume name (10 characters, pad with spaces) */
1382   UINT16BE totAUs;      /* total number of AUs */
1383   UINT8 secspertrack;      /* HFDC: sectors per track (typically 32) */
1384                     /* SCSI: reserved */
1385   union
1386   {
1387      struct
1388      {
1389         UINT8 id[3];   /* V1 VIB: 'WIN' */
1390      } vib_v1;
1391
1392      struct            /* V2 VIB: extra params */
1393      {
1394         UINT8 res_AUs;   /* # AUs reserved for vib, bitmap, ddr, fdir and fdr, divided by 64 */
1395         UINT8 step_spd;   /* HFDC: step speed (0-7) */
1396                     /* SCSI: reserved */
1397         UINT8 red_w_cur;/* HFDC: reduced write current cylinder, divided by 8 */
1398                     /* SCSI: reserved */
1399      } vib_v2;
1400
1401      struct
1402      {
1403         UINT8 id[3];   /* DDR: 'DIR' */
1404      } ddr;
1405   } u;
1406   UINT16BE params;      /* bits 0-3: sectors/AU - 1 */
1407                     /* HFDC: */
1408                        /* bits 4-7: # heads - 1 */
1409                        /* bit 8: V1: buffered head stepping flag */
1410                        /*        V2: reserved */
1411                        /* bit 9-15: write precompensation track, divided by 16 */
1412                     /* SCSI: */
1413                        /* bits 4-15: reserved */
1414   ti99_date_time creation;/* date and time of creation */
1415   UINT8 num_files;      /* number of files in directory */
1416   UINT8 num_subdirs;      /* number of subdirectories in directory */
1417   UINT16BE fdir_AU;      /* points to root directory fdir */
1418   union
1419   {
1420      struct
1421      {
1422         UINT16BE dsk1_AU;   /* HFDC: points to current dsk1 emulation image (0 if none) */
1423                        /* SCSI: reserved */
1424      } vib;
1425
1426      struct
1427      {
1428         UINT16BE parent_ddr_AU;   /* points to parent directory DDR */
1429      } ddr;
1430   } u2;
1431   UINT16BE subdir_AU[114];/* points to all subdirectory DDRs */
1432} win_vib_ddr;
1433
1434/*
1435   AU format
1436*/
1437typedef struct ti99_AUformat
1438{
1439   int totAUs;            /* total number of AUs */
1440   int physrecsperAU;      /* number of 256-byte physical records per AU */
1441} ti99_AUformat;
1442
1443/*
1444   DSK directory reference: 0 for root, 1 for 1st subdir, 2 for 2nd subdir, 3
1445   for 3rd subdir
1446*/
1447/*typedef int dir_ref;*/
1448
1449/*
1450   catalog entry (used for in-memory catalog)
1451*/
1452typedef struct dir_entry
1453{
1454   UINT16 dir_ptr;         /* DSK: unused */
1455                     /* WIN: AU address of the DDR for this directory */
1456   char name[10];         /* name of this directory (copied from the VIB for DSK, DDR for WIN) */
1457} dir_entry;
1458
1459typedef struct file_entry
1460{
1461   UINT16 fdr_ptr;         /* DSK: aphysrec address of the FDR for this file */
1462                     /* WIN: AU address of the FDR for this file */
1463   char name[10];         /* name of this file (copied from FDR) */
1464} file_entry;
1465
1466typedef struct ti99_catalog
1467{
1468   int num_subdirs;      /* number of subdirectories */
1469   int num_files;         /* number of files */
1470   dir_entry subdirs[114];   /* description of each subdir */
1471   file_entry files[128];   /* description of each file */
1472} ti99_catalog;
1473
1474/*
1475   level-2 disk image descriptor
1476*/
1477typedef struct ti99_lvl2_imgref_dsk
1478{
1479   UINT16 totphysrecs;            /* total number of aphysrecs (extracted from vib record in aphysrec 0) */
1480   ti99_catalog catalogs[4];      /* catalog of root directory and up to 3 subdirectories */
1481   UINT16 fdir_aphysrec[4];      /* fdir aphysrec address for root directory
1482                              and up to 3 subdirectories */
1483} ti99_lvl2_imgref_dsk;
1484
1485typedef struct ti99_lvl2_imgref_win
1486{
1487   enum
1488   {
1489      win_vib_v1,
1490      win_vib_v2
1491   } vib_version;         /* version of the vib record in aphysrec 0 (see win_vib_ddr) */
1492} ti99_lvl2_imgref_win;
1493
1494typedef struct ti99_lvl2_imgref
1495{
1496   ti99_lvl1_imgref l1_img;/* image format, imgtool image handle, image geometry */
1497   ti99_AUformat AUformat;   /* AU format */
1498   int data_offset;      /* In order to reduce seek times when searching the
1499                        disk for a given file name, fdr (and ddr, and
1500                        fdir) records are preferentially allocated in
1501                        AUs n to data_offset, whereas data records are
1502                        preferentially allocated in AUs starting at
1503                        data_offset. */
1504                     /* With the DSK disk structure, n is always 2 (if 1
1505                        physrec per AU) or 1 (if 2 physrecs per AU or
1506                        more), and data_offset is arbitrarily chosen as
1507                        34. */
1508                     /* With the WIN disk structure, n depends on the
1509                        size of the volume bitmap, which itself depends
1510                        on the number of AUs on disk (we always have n
1511                        <= 33), and data_offset is read from the vib
1512                        record (except with the obsolete v1 VIB, where
1513                        we use a default value of 64). */
1514   char vol_name[10];      /* cached volume name (extracted from vib record in aphysrec 0) */
1515
1516   UINT8 abm[8192];      /* allocation bitmap */
1517
1518   enum
1519   {
1520      L2I_DSK,
1521      L2I_WIN
1522   } type;               /* structure format */
1523
1524   union
1525   {
1526      ti99_lvl2_imgref_dsk dsk;
1527      ti99_lvl2_imgref_win win;
1528   } u;               /* structure-specific info */
1529} ti99_lvl2_imgref;
1530
1531/*
1532   file flags found in fdr (and tifiles)
1533*/
1534enum
1535{
1536   fdr99_f_program   = 0x01,   /* set for program files */
1537   fdr99_f_int      = 0x02,   /* set for binary files */
1538   fdr99_f_wp      = 0x08,   /* set if file is write-protected */
1539   /*fdr99_f_backup   = 0x10,*/   /* set if file has been modified since last backup */
1540   /*fdr99_f_dskimg   = 0x20,*/   /* set if file is a DSK image (HFDC HD only) */
1541   fdr99_f_var      = 0x80   /* set if file uses variable-length records*/
1542};
1543
1544/*
1545   DSK FDR record
1546*/
1547typedef struct dsk_fdr
1548{
1549   char name[10];         /* file name (10 characters, pad with spaces) */
1550   UINT16BE xreclen;      /* extended record len: if record len is >= 256, */
1551                        /* reclen is set to 0 and the actual reclen is */
1552                        /* stored here (Myarc HFDC only).  TI reserved */
1553                        /* this  field for data chain pointer extension, */
1554                        /* but this was never implemented. */
1555   UINT8 flags;         /* file status flags (see enum above) */
1556   UINT8 recsperphysrec;   /* logical records per physrec */
1557                        /* ignored for variable length record files and */
1558                        /* program files */
1559   UINT16BE fphysrecs;      /* file length in physrecs */
1560                        /* Note that the HFDC defines this field as the */
1561                        /* number of allocated physrecs in the cluster */
1562                        /* chain (i.e. rounded on the next AU */
1563                        /* boundary), so level-3 routines should use */
1564                        /* the fixrecs field instead to determine the */
1565                        /* logical lenght of field.  IIRC, the HFDC */
1566                        /* implementation is regarded as a bug because */
1567                        /* program files do not define the fixrecs field */
1568                        /* field, so program field saved by the HFDC */
1569                        /* DSR may be larger whan they should. */
1570   UINT8 eof;            /* EOF offset in last physrec for variable length */
1571                        /* record files and program files (0->256)*/
1572   UINT8 reclen;         /* logical record size in bytes ([1,255] 0->256) */
1573                        /* Maximum allowable record size for variable */
1574                        /* length record files.  Reserved for program */
1575                        /* files (set to 0).  Set to 0 if reclen >=256 */
1576                        /* (HFDC only). */
1577   UINT16LE fixrecs;      /* file length in logical records */
1578                        /* For variable length record files, number of */
1579                        /* 256-byte records actually used. */
1580   ti99_date_time creation;/* date and time of creation (HFDC and BwG only; */
1581                        /* reserved in TI) */
1582   ti99_date_time update;   /* date and time of last write to file (HFDC and */
1583                        /* BwG only; reserved in TI) */
1584   UINT8 clusters[76][3];   /* data cluster table: 0 through 76 entries (3 */
1585                        /* bytes each), one entry for each file cluster. */
1586                        /* 12 bits: address of first AU of cluster */
1587                        /* 12 bits: offset of last 256-byte record in cluster */
1588} dsk_fdr;
1589
1590/*
1591   WIN FDR record
1592*/
1593typedef struct win_fdr
1594{
1595   char name[10];         /* file name (10 characters, pad with spaces) */
1596   UINT16BE xreclen;      /* extended record len: if record len is >= 256, */
1597                        /* reclen is set to 0 and the actual reclen is */
1598                        /* stored here (Myarc HFDC only).  TI reserved */
1599                        /* this  field for data chain pointer extension, */
1600                        /* but this was never implemented. */
1601   UINT8 flags;         /* file status flags (see enum above) */
1602   UINT8 recsperphysrec;   /* logical records per physrec */
1603                        /* ignored for variable length record files and */
1604                        /* program files */
1605   UINT16BE fphysrecs_LSW;   /* eldest FDR: file length in physrecs */
1606                        /* Note that the HFDC defines this field as the */
1607                        /* number of allocated physrecs in the cluster */
1608                        /* chain (i.e. rounded on the next AU */
1609                        /* boundary), so level-3 routines should use */
1610                        /* the fixrecs field instead to determine the */
1611                        /* logical lenght of field.  IIRC, the HFDC */
1612                        /* implementation is regarded as a bug because */
1613                        /* program files do not define the fixrecs field */
1614                        /* field, so program field saved by the HFDC */
1615                        /* DSR may be larger whan they should. */
1616                     /* other sibling FDRs: index of the first file */
1617                        /* physrec in this particular sibling FDR */
1618   UINT8 eof;            /* EOF offset in last physrec for variable length */
1619                        /* record files and program files (0->256)*/
1620   UINT8 reclen;         /* logical record size in bytes ([1,255]) */
1621                        /* Maximum allowable record size for variable */
1622                        /* length record files.  Reserved for program */
1623                        /* files (set to 0).  Set to 0 if reclen >=256 */
1624                        /* (HFDC only). */
1625   UINT16LE fixrecs_LSW;   /* file length in logical records */
1626                        /* For variable length record files, number of */
1627                        /* 256-byte records actually used. */
1628   ti99_date_time creation;/* date and time of creation */
1629   ti99_date_time update;   /* date and time of last write to file */
1630
1631   char id[2];            /* 'FI' */
1632   UINT16BE prevsibFDR_AU;   /* address of the AU where previous sibling FDR is */
1633                        /* (see also xinfo_LSB) */
1634   UINT16BE nextsibFDR_AU;   /* address of the AU where next sibling FDR is */
1635                        /* (see also xinfo_LSB) */
1636   UINT16BE sibFDR_AUlen;   /* total number of data AUs allocated in this particular sibling FDR */
1637   UINT16BE parent_FDIR_AU;/* FDIR the file is listed in */
1638   UINT8 xinfo_MSB;      /* extended information (MSByte) */
1639                        /* bits 0-3: MSN of fphysrecs */
1640                        /* bits 4-7: MSN of fixrecs */
1641   UINT8 xinfo_LSB;      /* extended information (LSByte) */
1642                        /* bits 8-11: physrec offset within AU for */
1643                           /* previous sibling FDR (see prevsibFDR_AU) */
1644                        /* bits 12-15: physrec offset within AU for */
1645                           /* next sibling FDR (see nextsibFDR_AU) */
1646   UINT16BE clusters[54][2];/* data cluster table: 0 through 54 entries (4 */
1647                        /* bytes each), one entry for each file cluster. */
1648                        /* 16 bits: address of first AU of cluster */
1649                        /* 16 bits: address of last AU of cluster */
1650} win_fdr;
1651
1652/*
1653   tifile header: stand-alone file
1654*/
1655typedef struct tifile_header
1656{
1657   char tifiles[8];      /* always '\7TIFILES' */
1658   UINT16BE fphysrecs;      /* file length in physrecs */
1659   UINT8 flags;         /* see enum above */
1660   UINT8 recsperphysrec;   /* records per physrec */
1661   UINT8 eof;            /* current position of eof in last physrec (0->255)*/
1662   UINT8 reclen;         /* bytes per record ([1,255] 0->256) */
1663   UINT16BE fixrecs;      /* file length in records */
1664   UINT8 res[128-16];      /* reserved */
1665                        /* * variant a: */
1666                           /* 112 chars: 0xCA53 repeated 56 times */
1667                        /* * variant b: */
1668                           /* 4 chars: unknown */
1669                           /* 108 chars: 0xCA53 repeated 54 times */
1670                        /* * variant c: */
1671                           /* 10 chars: original TI file name filed with spaces */
1672                           /* 102 chars: spaces */
1673                        /* * variant d: */
1674                           /* 10 chars: original TI file name filed with spaces */
1675                           /* 2 chars: CR+LF */
1676                           /* 98 chars: spaces */
1677                           /* 2 chars: CR+LF */
1678                        /* * variant e: */
1679                           /* 10 chars: original TI file name */
1680                           /* 4 bytes: unknown */
1681                           /* 4 bytes: time & date of creation */
1682                           /* 4 bytes: time & date of last update */
1683                           /* 90 chars: spaces */
1684                        /* * variant f: */
1685                           /* 6 bytes: 'MYTERM' */
1686                           /* 4 bytes: time & date of creation */
1687                           /* 4 bytes: time & date of last update */
1688                           /* 2 bytes: unknown (always >0000) */
1689                           /* 96 chars: 0xCA53 repeated 56 times */
1690} tifile_header;
1691
1692/*
1693   level-2 file descriptor
1694*/
1695typedef struct ti99_lvl2_fileref_dsk
1696{
1697   ti99_lvl2_imgref *l2_img;
1698   int fdr_aphysrec;
1699   dsk_fdr fdr;
1700} ti99_lvl2_fileref_dsk;
1701
1702typedef struct ti99_lvl2_fileref_win
1703{
1704   ti99_lvl2_imgref *l2_img;
1705   unsigned fphysrecs;            /* copy of field in the eldest FDR */
1706   unsigned eldestfdr_aphysrec;   /* aphysrec address of the eldest FDR */
1707   unsigned curfdr_aphysrec;      /* aphysrec address of the currently open sibling FDR */
1708   win_fdr curfdr;               /* buffer with currently open sibling FDR */
1709} ti99_lvl2_fileref_win;
1710
1711typedef struct ti99_lvl2_fileref_tifiles
1712{
1713   imgtool_stream *file_handle;
1714   tifile_header hdr;
1715} ti99_lvl2_fileref_tifiles;
1716
1717typedef struct ti99_lvl2_fileref
1718{
1719   enum
1720   {
1721      L2F_DSK,
1722      L2F_WIN,
1723      L2F_TIFILES
1724   } type;
1725   union
1726   {
1727      ti99_lvl2_fileref_dsk dsk;
1728      ti99_lvl2_fileref_win win;
1729      ti99_lvl2_fileref_tifiles tifiles;
1730   } u;
1731} ti99_lvl2_fileref;
1732
1733
1734
1735/*
1736   Compare two (possibly empty) catalog entry for qsort
1737*/
1738static int cat_file_compare_qsort(const void *p1, const void *p2)
1739{
1740   const file_entry *entry1 = p1;
1741   const file_entry *entry2 = p2;
1742
1743   if ((entry1->fdr_ptr == 0) && (entry2->fdr_ptr == 0))
1744      return 0;
1745   else if (entry1->fdr_ptr == 0)
1746      return +1;
1747   else if (entry2->fdr_ptr == 0)
1748      return -1;
1749   else
1750      return memcmp(entry1->name, entry2->name, 10);
1751}
1752
1753static int cat_dir_compare_qsort(const void *p1, const void *p2)
1754{
1755   const dir_entry *entry1 = p1;
1756   const dir_entry *entry2 = p2;
1757
1758   if ((entry1->dir_ptr == 0) && (entry2->dir_ptr == 0))
1759      return 0;
1760   else if (entry1->dir_ptr == 0)
1761      return +1;
1762   else if (entry2->dir_ptr == 0)
1763      return -1;
1764   else
1765      return memcmp(entry1->name, entry2->name, 10);
1766}
1767
1768/*
1769   Read a directory catalog from disk image
1770
1771   l2_img: image reference
1772   aphysrec: physical record address of the FDIR
1773   dest: pointer to the destination buffer where the catalog should be written
1774
1775   Return an error code if there was an error, 0 otherwise.
1776*/
1777static int dsk_read_catalog(ti99_lvl2_imgref *l2_img, int aphysrec, ti99_catalog *dest)
1778{
1779   int totphysrecs = l2_img->u.dsk.totphysrecs;
1780   UINT16BE fdir_buf[128];
1781   dsk_fdr fdr;
1782   int i;
1783   int reply;
1784
1785
1786   /* Read FDIR record */
1787   reply = read_absolute_physrec(& l2_img->l1_img, aphysrec, fdir_buf);
1788   if (reply)
1789      return IMGTOOLERR_READERROR;
1790
1791   /* Copy FDIR info to catalog structure */
1792   for (i=0; i<128; i++)
1793      dest->files[i].fdr_ptr = get_UINT16BE(fdir_buf[i]);
1794
1795   /* Check FDIR pointers and check and extract file names from DDRs */
1796   for (i=0; i<128; i++)
1797   {
1798      if (dest->files[i].fdr_ptr >= totphysrecs)
1799      {
1800         return IMGTOOLERR_CORRUPTIMAGE;
1801      }
1802      else if (dest->files[i].fdr_ptr)
1803      {
1804         reply = read_absolute_physrec(& l2_img->l1_img, dest->files[i].fdr_ptr, &fdr);
1805         if (reply)
1806            return IMGTOOLERR_READERROR;
1807
1808         /* check and copy file name */
1809         if (check_fname(fdr.name))
1810            return IMGTOOLERR_CORRUPTIMAGE;
1811         memcpy(dest->files[i].name, fdr.name, 10);
1812      }
1813   }
1814
1815   /* Check catalog */
1816   for (i=0; i<127; i++)
1817   {
1818      if (((! dest->files[i].fdr_ptr) && dest->files[i+1].fdr_ptr)
1819         || ((dest->files[i].fdr_ptr && dest->files[i+1].fdr_ptr) && (memcmp(dest->files[i].name, dest->files[i+1].name, 10) >= 0)))
1820      {
1821         /* if the catalog is not sorted, we repair it */
1822         qsort(dest->files, sizeof(dest->files)/sizeof(dest->files[0]), sizeof(dest->files[0]),
1823               cat_file_compare_qsort);
1824         break;
1825      }
1826   }
1827
1828   /* Set file count */
1829   for (i=0; (i<128) && (dest->files[i].fdr_ptr != 0); i++)
1830      ;
1831   dest->num_files = i;
1832
1833   /* Set subdir count to 0 (subdirs are loaded elsewhere) */
1834   dest->num_subdirs = 0;
1835
1836   return 0;
1837}
1838
1839/*
1840   Read a directory catalog from disk image
1841
1842   l2_img: image reference
1843   DDR_AU: AU address of the VIB/DDR
1844   dest: pointer to the destination buffer where the catalog should be written
1845
1846   Return an error code if there was an error, 0 otherwise.
1847*/
1848static int win_read_catalog(ti99_lvl2_imgref *l2_img, int DDR_AU, ti99_catalog *dest)
1849{
1850   win_vib_ddr ddr_buf;
1851   UINT16BE fdir_buf[128];
1852   win_fdr fdr_buf;
1853   int i;
1854   int reply;
1855
1856
1857   /* Read DDR record */
1858   reply = read_absolute_physrec(& l2_img->l1_img, DDR_AU*l2_img->AUformat.physrecsperAU, &ddr_buf);
1859   if (reply)
1860      return IMGTOOLERR_READERROR;
1861
1862   /* sanity checks */
1863   if ((ddr_buf.num_files > 127) || (ddr_buf.num_subdirs > 114) || (get_UINT16BE(ddr_buf.fdir_AU) > l2_img->AUformat.totAUs))
1864      return IMGTOOLERR_CORRUPTIMAGE;
1865
1866   /* set file count and subdir count */
1867   dest->num_files = ddr_buf.num_files;
1868   dest->num_subdirs = ddr_buf.num_subdirs;
1869
1870   /* Copy DDR info to catalog structure */
1871   for (i=0; i<ddr_buf.num_subdirs; i++)
1872      dest->subdirs[i].dir_ptr = get_UINT16BE(ddr_buf.subdir_AU[i]);
1873
1874   /* Read FDIR record */
1875   reply = read_absolute_physrec(& l2_img->l1_img, get_UINT16BE(ddr_buf.fdir_AU)*l2_img->AUformat.physrecsperAU, fdir_buf);
1876   if (reply)
1877      return IMGTOOLERR_READERROR;
1878
1879   /* Copy FDIR info to catalog structure */
1880   for (i=0; i<dest->num_files; i++)
1881      dest->files[i].fdr_ptr = get_UINT16BE(fdir_buf[i]);
1882
1883   /* Check DDR pointers and check and extract file names from FDRs */
1884   for (i=0; i<dest->num_subdirs; i++)
1885   {
1886      if (dest->subdirs[i].dir_ptr >= l2_img->AUformat.totAUs)
1887      {
1888         return IMGTOOLERR_CORRUPTIMAGE;
1889      }
1890      else if (dest->subdirs[i].dir_ptr)
1891      {
1892         reply = read_absolute_physrec(& l2_img->l1_img, dest->subdirs[i].dir_ptr*l2_img->AUformat.physrecsperAU, &ddr_buf);
1893         if (reply)
1894            return IMGTOOLERR_READERROR;
1895
1896         /* check and copy file name */
1897         if (check_fname(ddr_buf.name))
1898            return IMGTOOLERR_CORRUPTIMAGE;
1899         memcpy(dest->subdirs[i].name, ddr_buf.name, 10);
1900      }
1901   }
1902
1903   /* Check FDIR pointers and check and extract file names from FDRs */
1904   for (i=0; i<dest->num_files; i++)
1905   {
1906      if (dest->files[i].fdr_ptr >= l2_img->AUformat.totAUs)
1907      {
1908         return IMGTOOLERR_CORRUPTIMAGE;
1909      }
1910      else if (dest->files[i].fdr_ptr)
1911      {
1912         reply = read_absolute_physrec(& l2_img->l1_img, dest->files[i].fdr_ptr*l2_img->AUformat.physrecsperAU, &fdr_buf);
1913         if (reply)
1914            return IMGTOOLERR_READERROR;
1915
1916         /* check and copy file name */
1917         if (check_fname(fdr_buf.name))
1918            return IMGTOOLERR_CORRUPTIMAGE;
1919         memcpy(dest->files[i].name, fdr_buf.name, 10);
1920      }
1921   }
1922
1923   /* Check catalog */
1924
1925   /* Check subdir order */
1926   for (i=0; i<dest->num_subdirs-1; i++)
1927   {
1928      if (((! dest->subdirs[i].dir_ptr) && dest->subdirs[i+1].dir_ptr)
1929         || ((dest->subdirs[i].dir_ptr && dest->subdirs[i+1].dir_ptr) && (memcmp(dest->subdirs[i].name, dest->subdirs[i+1].name, 10) >= 0)))
1930      {
1931         /* if the subdir catalog is not sorted, we repair it */
1932         qsort(dest->subdirs, dest->num_subdirs, sizeof(dest->subdirs[0]), cat_dir_compare_qsort);
1933         break;
1934      }
1935   }
1936
1937   /* Fix subdir count */
1938   while (dest->num_subdirs && (dest->subdirs[dest->num_subdirs-1].dir_ptr == 0))
1939      dest->num_subdirs--;
1940
1941   /* Check file order */
1942   for (i=0; i<dest->num_files-1; i++)
1943   {
1944      if (((! dest->files[i].fdr_ptr) && dest->files[i+1].fdr_ptr)
1945         || ((dest->files[i].fdr_ptr && dest->files[i+1].fdr_ptr) && (memcmp(dest->files[i].name, dest->files[i+1].name, 10) >= 0)))
1946      {
1947         /* if the file catalog is not sorted, we repair it */
1948         qsort(dest->files, dest->num_files, sizeof(dest->files[0]), cat_file_compare_qsort);
1949         break;
1950      }
1951   }
1952
1953   /* Fix file count */
1954   while (dest->num_files && (dest->files[dest->num_files-1].fdr_ptr == 0))
1955      dest->num_files--;
1956
1957   return 0;
1958}
1959
1960/*
1961   Search for a file path on a floppy image
1962
1963   l2_img: image reference
1964   fpath: path of the file to search
1965   parent_ref_valid: set to TRUE if either the file was found or the file was
1966      not found but its parent dir was
1967   parent_ref: reference to parent dir (0 for root)
1968   out_is_dir: TRUE if element is a directory
1969   catalog_index: on output, index of file catalog entry (may be NULL)
1970*/
1971static int dsk_find_catalog_entry(ti99_lvl2_imgref *l2_img, const char *fpath, int *parent_ref_valid, int *parent_ref, int *out_is_dir, int *catalog_index)
1972{
1973   int i;
1974   const ti99_catalog *cur_catalog;
1975   const char *element_start, *element_end;
1976   int element_len;
1977   char element[10];
1978   int is_dir = FALSE;
1979
1980
1981   cur_catalog = & l2_img->u.dsk.catalogs[0];
1982   if (parent_ref_valid)
1983      (* parent_ref_valid) = FALSE;
1984   if (parent_ref)
1985      *parent_ref = 0;
1986
1987   element_start = fpath;
1988   do
1989   {
1990      /* find next path element */
1991      element_end = strchr(element_start, '.');
1992      element_len = element_end ? (element_end - element_start) : strlen(element_start);
1993      if ((element_len > 10) || (element_len == 0))
1994         return IMGTOOLERR_BADFILENAME;
1995      /* last path element */
1996      if ((!element_end) && parent_ref_valid)
1997         (* parent_ref_valid) = TRUE;
1998
1999      /* generate file name */
2000      memcpy(element, element_start, element_len);
2001      memset(element+element_len, ' ', 10-element_len);
2002
2003      /* search entry in subdirectories */
2004      for (i = 0; i<cur_catalog->num_subdirs; i++)
2005      {
2006         if (! memcmp(element, cur_catalog->subdirs[i].name, 10))
2007         {
2008            is_dir = TRUE;
2009            break;
2010         }
2011      }
2012
2013      /* if it failed, search entry in files */
2014      if (i == cur_catalog->num_subdirs)
2015      {
2016         for (i = 0; i<cur_catalog->num_files; i++)
2017         {
2018            if (! memcmp(element, cur_catalog->files[i].name, 10))
2019            {
2020               is_dir = FALSE;
2021               break;
2022            }
2023         }
2024         /* exit if not found */
2025         if (i == cur_catalog->num_files)
2026         {
2027            return IMGTOOLERR_FILENOTFOUND;
2028         }
2029      }
2030
2031      /* iterate */
2032      if (element_end)
2033      {
2034         element_start = element_end+1;
2035
2036         if (! is_dir)
2037            /* this is not a directory */
2038            return IMGTOOLERR_BADFILENAME;
2039
2040         /* initialize cur_catalog */
2041         cur_catalog = & l2_img->u.dsk.catalogs[i+1];
2042         if (parent_ref)
2043            *parent_ref = i+1;
2044      }
2045      else
2046         element_start = NULL;
2047   }
2048   while (element_start);
2049
2050   if (out_is_dir)
2051      *out_is_dir = is_dir;
2052
2053   if (catalog_index)
2054      *catalog_index = i;
2055
2056   return 0;
2057}
2058
2059/*
2060   Search for a file path on a harddisk image
2061
2062   l2_img: image reference
2063   fpath: path of the file to search
2064   parent_ref_valid: set to TRUE if either the file was found or the file was
2065      not found but its parent dir was
2066   parent_ddr_AU: parent DDR AU address (0 for root)
2067   parent_catalog: catalog of parent dir (cannot be NULL)
2068   out_is_dir: TRUE if element is a directory
2069   catalog_index: on output, index of file catalog entry (may be NULL)
2070*/
2071static int win_find_catalog_entry(ti99_lvl2_imgref *l2_img, const char *fpath,
2072                           int *parent_ref_valid, int *parent_ddr_AU, ti99_catalog *parent_catalog,
2073                           int *out_is_dir, int *catalog_index)
2074{
2075   int i;
2076   const char *element_start, *element_end;
2077   int element_len;
2078   char element[10];
2079   int is_dir = FALSE;
2080   int errorcode;
2081
2082   if (parent_ref_valid)
2083      (* parent_ref_valid) = FALSE;
2084   if (parent_ddr_AU)
2085      *parent_ddr_AU = 0;
2086
2087   errorcode = win_read_catalog(l2_img, 0, parent_catalog);
2088   if (errorcode)
2089      return errorcode;
2090
2091   element_start = fpath;
2092   do
2093   {
2094      /* find next path element */
2095      element_end = strchr(element_start, '.');
2096      element_len = element_end ? (element_end - element_start) : strlen(element_start);
2097      if ((element_len > 10) || (element_len == 0))
2098         return IMGTOOLERR_BADFILENAME;
2099      /* last path element */
2100      if ((!element_end) && parent_ref_valid)
2101         (* parent_ref_valid) = TRUE;
2102
2103      /* generate file name */
2104      memcpy(element, element_start, element_len);
2105      memset(element+element_len, ' ', 10-element_len);
2106
2107      /* search entry in subdirectories */
2108      for (i = 0; i<parent_catalog->num_subdirs; i++)
2109      {
2110         if (! memcmp(element, parent_catalog->subdirs[i].name, 10))
2111         {
2112            is_dir = TRUE;
2113            break;
2114         }
2115      }
2116
2117      /* if it failed, search entry in files */
2118      if (i == parent_catalog->num_subdirs)
2119      {
2120         for (i = 0; i<parent_catalog->num_files; i++)
2121         {
2122            if (! memcmp(element, parent_catalog->files[i].name, 10))
2123            {
2124               is_dir = FALSE;
2125               break;
2126            }
2127         }
2128         /* exit if not found */
2129         if (i == parent_catalog->num_files)
2130         {
2131            return IMGTOOLERR_FILENOTFOUND;
2132         }
2133      }
2134
2135      /* iterate */
2136      if (element_end)
2137      {
2138         element_start = element_end+1;
2139
2140         if (! is_dir)
2141            /* this is not a directory */
2142            return IMGTOOLERR_BADFILENAME;
2143
2144         if (parent_ddr_AU)
2145            *parent_ddr_AU = parent_catalog->subdirs[i].dir_ptr;
2146
2147         errorcode = win_read_catalog(l2_img, parent_catalog->subdirs[i].dir_ptr, parent_catalog);
2148         if (errorcode)
2149            return errorcode;
2150      }
2151      else
2152         element_start = NULL;
2153   }
2154   while (element_start);
2155
2156   if (out_is_dir)
2157      *out_is_dir = is_dir;
2158
2159   if (catalog_index)
2160      *catalog_index = i;
2161
2162   return 0;
2163}
2164
2165/*
2166   Allocate one AU on disk, for use as a fdr record
2167
2168   l2_img: image reference
2169   fdr_AU: on output, address of allocated AU
2170*/
2171static int alloc_fdr_AU(ti99_lvl2_imgref *l2_img, unsigned *fdr_AU)
2172{
2173   int totAUs = l2_img->AUformat.totAUs;
2174   int i;
2175
2176   for (i=0; i<totAUs; i++)
2177   {
2178      if (! (l2_img->abm[i >> 3] & (1 << (i & 7))))
2179      {
2180         *fdr_AU = i;
2181         l2_img->abm[i >> 3] |= 1 << (i & 7);
2182
2183         return 0;
2184      }
2185   }
2186
2187   return IMGTOOLERR_NOSPACE;
2188}
2189
2190INLINE int get_dsk_fdr_cluster_baseAU(ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index)
2191{
2192   int reply;
2193
2194   /* read base AU/physrec for this cluster */
2195   reply = ((fdr->clusters[cluster_index][1] & 0xf) << 8) | fdr->clusters[cluster_index][0];
2196   /* convert to AU address */
2197   if (l2_img->AUformat.physrecsperAU <= 2)
2198      reply /= l2_img->AUformat.physrecsperAU;
2199
2200   return reply;
2201}
2202
2203INLINE int get_dsk_fdr_cluster_baseaphysrec(ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index)
2204{
2205   int reply;
2206
2207   /* read base AU/physrec for this cluster */
2208   reply = ((fdr->clusters[cluster_index][1] & 0xf) << 8) | fdr->clusters[cluster_index][0];
2209   /* convert to physrec address */
2210   if (l2_img->AUformat.physrecsperAU > 2)
2211      reply *= l2_img->AUformat.physrecsperAU;
2212
2213   return reply;
2214}
2215
2216INLINE int get_dsk_fdr_cluster_lastfphysrec(dsk_fdr *fdr, int cluster_index)
2217{
2218   return (fdr->clusters[cluster_index][2] << 4) | (fdr->clusters[cluster_index][1] >> 4);
2219}
2220
2221INLINE void set_dsk_fdr_cluster_lastfphysrec(dsk_fdr *fdr, int cluster_index, int data)
2222{
2223   fdr->clusters[cluster_index][1] = (fdr->clusters[cluster_index][1] & 0x0f) | (data << 4);
2224   fdr->clusters[cluster_index][2] = data >> 4;
2225}
2226
2227INLINE void set_dsk_fdr_cluster(ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index, int baseAU, int lastfphysrec)
2228{
2229   /* convert AU address to FDR value */
2230   if (l2_img->AUformat.physrecsperAU <= 2)
2231      baseAU *= l2_img->AUformat.physrecsperAU;
2232
2233   /* write cluster entry */
2234   fdr->clusters[cluster_index][0] = baseAU;
2235   fdr->clusters[cluster_index][1] = ((baseAU >> 8) & 0x0f) | (lastfphysrec << 4);
2236   fdr->clusters[cluster_index][2] = lastfphysrec >> 4;
2237}
2238
2239INLINE unsigned get_win_fdr_fphysrecs(win_fdr *fdr)
2240{
2241   return (((unsigned) fdr->xinfo_MSB << 12) & 0xf0000) | get_UINT16BE(fdr->fphysrecs_LSW);
2242}
2243
2244INLINE void set_win_fdr_fphysrecs(win_fdr *fdr, unsigned data)
2245{
2246   fdr->xinfo_MSB = (fdr->xinfo_MSB & 0x0f) | ((data >> 12) & 0xf0);
2247   set_UINT16BE(&fdr->fphysrecs_LSW, data & 0xffff);
2248}
2249
2250INLINE unsigned get_win_fdr_fixrecs(win_fdr *fdr)
2251{
2252   return (((unsigned) fdr->xinfo_MSB << 16) & 0xf0000) | get_UINT16LE(fdr->fixrecs_LSW);
2253}
2254
2255INLINE void set_win_fdr_fixrecs(win_fdr *fdr, unsigned data)
2256{
2257   fdr->xinfo_MSB = (fdr->xinfo_MSB & 0xf0) | ((data >> 16) & 0x0f);
2258   set_UINT16LE(&fdr->fixrecs_LSW, data & 0xffff);
2259}
2260
2261INLINE unsigned get_win_fdr_prevsibFDR_aphysrec(ti99_lvl2_imgref *l2_img, win_fdr *fdr)
2262{
2263   unsigned prevsibFDR_AU = get_UINT16BE(fdr->prevsibFDR_AU);
2264
2265   return prevsibFDR_AU
2266         ? (prevsibFDR_AU * l2_img->AUformat.physrecsperAU + ((fdr->xinfo_LSB >> 4) & 0xf))
2267         : 0;
2268}
2269
2270INLINE unsigned get_win_fdr_nextsibFDR_aphysrec(ti99_lvl2_imgref *l2_img, win_fdr *fdr)
2271{
2272   unsigned nextsibFDR_AU = get_UINT16BE(fdr->nextsibFDR_AU);
2273
2274   return nextsibFDR_AU
2275         ? (nextsibFDR_AU * l2_img->AUformat.physrecsperAU + (fdr->xinfo_LSB & 0xf))
2276         : 0;
2277}
2278
2279INLINE unsigned get_win_fdr_cursibFDR_basefphysrec(win_fdr *fdr)
2280{
2281   return get_UINT16BE(fdr->prevsibFDR_AU) ? get_win_fdr_fphysrecs(fdr) : 0;
2282}
2283
2284/*
2285   Advance to next sibling FDR
2286*/
2287static int win_goto_next_sibFDR(ti99_lvl2_fileref_win *win_file)
2288{
2289   if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) == 0)
2290      return IMGTOOLERR_UNEXPECTED;
2291
2292   win_file->curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(win_file->l2_img, &win_file->curfdr);
2293   if (read_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2294      return IMGTOOLERR_READERROR;
2295
2296   return 0;
2297}
2298
2299/*
2300   Back to previous sibling FDR
2301*/
2302static int win_goto_prev_sibFDR(ti99_lvl2_fileref_win *win_file)
2303{
2304   if (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) == 0)
2305      return IMGTOOLERR_UNEXPECTED;
2306
2307   win_file->curfdr_aphysrec = get_win_fdr_prevsibFDR_aphysrec(win_file->l2_img, &win_file->curfdr);
2308   if (read_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2309      return IMGTOOLERR_READERROR;
2310
2311   return 0;
2312}
2313
2314/*
2315   Append a new sibling FDR at the end of the sibling FDR list, and open it.
2316
2317   You must have gone to the end of the list.
2318*/
2319static int win_alloc_sibFDR(ti99_lvl2_fileref_win *win_file)
2320{
2321   unsigned oldfdr_AU, oldfdr_physrecinAU;
2322   unsigned newfdr_AU, newfdr_physrecinAU;
2323   int allocated = FALSE;
2324   int errorcode;
2325   unsigned cursibFDR_basefphysrec;
2326
2327   if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU))
2328      return IMGTOOLERR_UNEXPECTED;
2329
2330   oldfdr_AU = win_file->curfdr_aphysrec / win_file->l2_img->AUformat.physrecsperAU;
2331   oldfdr_physrecinAU = win_file->curfdr_aphysrec % win_file->l2_img->AUformat.physrecsperAU;
2332
2333   if (oldfdr_physrecinAU != (win_file->l2_img->AUformat.physrecsperAU - 1))
2334   {   /* current AU is not full */
2335      newfdr_AU = oldfdr_AU;
2336      newfdr_physrecinAU = oldfdr_physrecinAU + 1;
2337   }
2338   else
2339   {   /* current AU is full: allocate another */
2340      errorcode = alloc_fdr_AU(win_file->l2_img, &newfdr_AU);
2341      if (errorcode)
2342         return errorcode;
2343      newfdr_physrecinAU = 0;
2344      allocated = TRUE;
2345   }
2346
2347   set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, newfdr_AU);
2348   win_file->curfdr.xinfo_LSB = (win_file->curfdr.xinfo_LSB & 0xf0) | newfdr_physrecinAU;
2349
2350   /* save current sibling FDR */
2351   if (write_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2352   {
2353      /* clear pointer */
2354      set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, 0);
2355      win_file->curfdr.xinfo_LSB = win_file->curfdr.xinfo_LSB & 0xf0;
2356      if (allocated)
2357         /* free AU */
2358         win_file->l2_img->abm[newfdr_AU >> 3] |= 1 << (newfdr_AU & 7);
2359      return IMGTOOLERR_WRITEERROR;
2360   }
2361
2362   /* now update in-memory structure to describe new sibling FDR */
2363   cursibFDR_basefphysrec = get_win_fdr_cursibFDR_basefphysrec(&win_file->curfdr)
2364                        + get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU;
2365
2366   set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, 0);
2367   set_UINT16BE(&win_file->curfdr.prevsibFDR_AU, oldfdr_AU);
2368   win_file->curfdr.xinfo_LSB = oldfdr_physrecinAU << 4;
2369
2370   win_file->curfdr_aphysrec = newfdr_AU * win_file->l2_img->AUformat.physrecsperAU + newfdr_physrecinAU;
2371
2372   set_win_fdr_fphysrecs(&win_file->curfdr, cursibFDR_basefphysrec);
2373   set_UINT16BE(&win_file->curfdr.sibFDR_AUlen, 0);
2374   memset(win_file->curfdr.clusters, 0, sizeof(win_file->curfdr.clusters));
2375
2376   return 0;
2377}
2378
2379/*
2380   Extend a file with nb_alloc_physrecs extra physrecs
2381
2382   dsk_file: file reference
2383   nb_alloc_physrecs: number of physical records to allocate
2384*/
2385static int dsk_alloc_file_physrecs(ti99_lvl2_fileref_dsk *dsk_file, int nb_alloc_physrecs)
2386{
2387   int totAUs = dsk_file->l2_img->AUformat.totAUs;
2388   int free_physrecs;
2389   int fphysrecs;
2390   int i;
2391   int cluster_index;
2392   int last_sec, p_last_sec = 0;
2393   int cur_block_seclen;
2394   int cluster_baseAU, cluster_AUlen;
2395   int first_best_block_baseAU = 0, first_best_block_seclen;
2396   int second_best_block_baseAU = 0, second_best_block_seclen;
2397   int search_start;
2398
2399   /* compute free space */
2400   free_physrecs = 0;
2401   for (i=0; i<totAUs; i++)
2402   {
2403      if (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2404         free_physrecs += dsk_file->l2_img->AUformat.physrecsperAU;
2405   }
2406
2407   /* check we have enough free space */
2408   if (free_physrecs < nb_alloc_physrecs)
2409      return IMGTOOLERR_NOSPACE;
2410
2411   /* current number of data physrecs in file */
2412   fphysrecs = get_UINT16BE(dsk_file->fdr.fphysrecs);
2413
2414   if (fphysrecs == 0)
2415   {   /* cluster array must be empty */
2416      cluster_index = 0;
2417   }
2418   else
2419   {   /* try to extend last block */
2420      last_sec = -1;
2421      for (cluster_index=0; cluster_index<76; cluster_index++)
2422      {
2423         p_last_sec = last_sec;
2424         last_sec = get_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index);
2425         if (last_sec >= (fphysrecs-1))
2426            break;
2427      }
2428      if (cluster_index == 76)
2429         /* that sucks */
2430         return IMGTOOLERR_CORRUPTIMAGE;
2431
2432      if (last_sec > (fphysrecs-1))
2433      {   /* some extra space has already been allocated */
2434         cur_block_seclen = last_sec - (fphysrecs-1);
2435         if (cur_block_seclen > nb_alloc_physrecs)
2436            cur_block_seclen = nb_alloc_physrecs;
2437
2438         fphysrecs += cur_block_seclen;
2439         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2440         nb_alloc_physrecs -= cur_block_seclen;
2441         if (! nb_alloc_physrecs)
2442            return 0;   /* done */
2443      }
2444
2445      /* round up to next AU boundary */
2446      last_sec = last_sec + dsk_file->l2_img->AUformat.physrecsperAU - (last_sec % dsk_file->l2_img->AUformat.physrecsperAU) - 1;
2447
2448      if (last_sec > (fphysrecs-1))
2449      {   /* some extra space has already been allocated */
2450         cur_block_seclen = last_sec - (fphysrecs-1);
2451         if (cur_block_seclen > nb_alloc_physrecs)
2452            cur_block_seclen = nb_alloc_physrecs;
2453
2454         fphysrecs += cur_block_seclen;
2455         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2456         set_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index, fphysrecs-1);
2457         nb_alloc_physrecs -= cur_block_seclen;
2458         if (! nb_alloc_physrecs)
2459            return 0;   /* done */
2460      }
2461
2462      /* read base AU address for this cluster */
2463      cluster_baseAU = get_dsk_fdr_cluster_baseAU(dsk_file->l2_img, &dsk_file->fdr, cluster_index);
2464      /* point past cluster end */
2465      cluster_baseAU += (last_sec-p_last_sec/*+file->l2_img->AUformat.physrecsperAU-1*/) / dsk_file->l2_img->AUformat.physrecsperAU;
2466      /* count free physrecs after last block */
2467      cur_block_seclen = 0;
2468      for (i=cluster_baseAU; (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7)))) && (cur_block_seclen < nb_alloc_physrecs) && (i < totAUs); i++)
2469         cur_block_seclen += dsk_file->l2_img->AUformat.physrecsperAU;
2470      if (cur_block_seclen)
2471      {   /* extend last block */
2472         if (cur_block_seclen > nb_alloc_physrecs)
2473            cur_block_seclen = nb_alloc_physrecs;
2474
2475         fphysrecs += cur_block_seclen;
2476         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2477         last_sec += cur_block_seclen;
2478         nb_alloc_physrecs -= cur_block_seclen;
2479         set_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index, last_sec);
2480         cluster_AUlen = (cur_block_seclen + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
2481         for (i=0; i<cluster_AUlen; i++)
2482            dsk_file->l2_img->abm[(i+cluster_baseAU) >> 3] |= 1 << ((i+cluster_baseAU) & 7);
2483         if (! nb_alloc_physrecs)
2484            return 0;   /* done */
2485      }
2486      cluster_index++;
2487      if (cluster_index == 76)
2488         /* that sucks */
2489         return IMGTOOLERR_NOSPACE;
2490   }
2491
2492   search_start = dsk_file->l2_img->data_offset;   /* initially, search for free space only in data space */
2493   while (nb_alloc_physrecs)
2494   {
2495      /* find smallest data block at least nb_alloc_physrecs in lenght, and largest data block less than nb_alloc_physrecs in lenght */
2496      first_best_block_seclen = INT_MAX;
2497      second_best_block_seclen = 0;
2498      for (i=search_start; i<totAUs; i++)
2499      {
2500         if (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2501         {   /* found one free block */
2502            /* compute its lenght */
2503            cluster_baseAU = i;
2504            cur_block_seclen = 0;
2505            while ((i<totAUs) && (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7)))))
2506            {
2507               cur_block_seclen += dsk_file->l2_img->AUformat.physrecsperAU;
2508               i++;
2509            }
2510            /* compare to previous best and second-best blocks */
2511            if ((cur_block_seclen < first_best_block_seclen) && (cur_block_seclen >= nb_alloc_physrecs))
2512            {
2513               first_best_block_baseAU = cluster_baseAU;
2514               first_best_block_seclen = cur_block_seclen;
2515               if (cur_block_seclen == nb_alloc_physrecs)
2516                  /* no need to search further */
2517                  break;
2518            }
2519            else if ((cur_block_seclen > second_best_block_seclen) && (cur_block_seclen < nb_alloc_physrecs))
2520            {
2521               second_best_block_baseAU = cluster_baseAU;
2522               second_best_block_seclen = cur_block_seclen;
2523            }
2524         }
2525      }
2526
2527      if (first_best_block_seclen != INT_MAX)
2528      {   /* found one contiguous block which can hold it all */
2529         fphysrecs += nb_alloc_physrecs;
2530         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2531
2532         set_dsk_fdr_cluster(dsk_file->l2_img, &dsk_file->fdr, cluster_index, first_best_block_baseAU, fphysrecs-1);
2533         cluster_AUlen = (nb_alloc_physrecs + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
2534         for (i=0; i<cluster_AUlen; i++)
2535            dsk_file->l2_img->abm[(i+first_best_block_baseAU) >> 3] |= 1 << ((i+first_best_block_baseAU) & 7);
2536
2537         nb_alloc_physrecs = 0;
2538      }
2539      else if (second_best_block_seclen != 0)
2540      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
2541         fphysrecs += second_best_block_seclen;
2542         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2543
2544         set_dsk_fdr_cluster(dsk_file->l2_img, &dsk_file->fdr, cluster_index, second_best_block_baseAU, fphysrecs-1);
2545         cluster_AUlen = (second_best_block_seclen + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
2546         for (i=0; i<cluster_AUlen; i++)
2547            dsk_file->l2_img->abm[(i+second_best_block_baseAU) >> 3] |= 1 << ((i+second_best_block_baseAU) & 7);
2548
2549         nb_alloc_physrecs -= second_best_block_seclen;
2550
2551         cluster_index++;
2552         if (cluster_index == 76)
2553            /* that sucks */
2554            return IMGTOOLERR_NOSPACE;
2555      }
2556      else if (search_start != 0)
2557      {   /* we did not find any free physrec in the data section of the disk */
2558         search_start = 0;   /* time to fall back to fdr space */
2559      }
2560      else
2561         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
2562   }
2563
2564   return 0;
2565}
2566
2567/*
2568   Extend a file with nb_alloc_physrecs extra physrecs
2569
2570   win_file: file reference
2571   nb_alloc_physrecs: number of physical records to allocate
2572*/
2573static int win_alloc_file_physrecs(ti99_lvl2_fileref_win *win_file, int nb_alloc_physrecs)
2574{
2575   int totAUs = win_file->l2_img->AUformat.totAUs;
2576   int free_physrecs;
2577   int fphysrecs;
2578   int i;
2579   int cluster_index;
2580   int num_fphysrec;
2581   int cur_block_seclen;
2582   int cluster_baseAU, cluster_AUlen;
2583   int first_best_block_baseAU = 0, first_best_block_seclen;
2584   int second_best_block_baseAU = 0, second_best_block_seclen;
2585   int search_start;
2586   int errorcode;
2587
2588   /* compute free space */
2589   free_physrecs = 0;
2590   for (i=0; i<totAUs; i++)
2591   {
2592      if (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2593         free_physrecs += win_file->l2_img->AUformat.physrecsperAU;
2594   }
2595
2596   /* check we have enough free space */
2597   if (free_physrecs < nb_alloc_physrecs)
2598      return IMGTOOLERR_NOSPACE;
2599
2600   /* move to last sibling non-empty FDR */
2601   while ((get_UINT16BE(win_file->curfdr.nextsibFDR_AU) != 0) &&
2602            (get_UINT16BE(win_file->curfdr.clusters[53][0]) != 0))
2603   {
2604      errorcode = win_goto_next_sibFDR(win_file);
2605      if (errorcode)
2606         return errorcode;
2607   }
2608   if ((get_UINT16BE(win_file->curfdr.clusters[0][0]) == 0) && (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) != 0))
2609   {   /* this is annoying: we have found a sibling FDR filled with 0s: rewind
2610      to last non-empty sibling if applicable */
2611      errorcode = win_goto_prev_sibFDR(win_file);
2612      if (errorcode)
2613         return errorcode;
2614   }
2615
2616   /* current number of data physrecs in file */
2617   fphysrecs = win_file->fphysrecs;
2618
2619   /* current number of allocated physrecs */
2620   num_fphysrec = get_win_fdr_cursibFDR_basefphysrec(&win_file->curfdr)
2621                  + get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU;
2622
2623   if (num_fphysrec > fphysrecs)
2624   {   /* some extra space has already been allocated */
2625      cur_block_seclen = num_fphysrec - fphysrecs;
2626      if (cur_block_seclen > nb_alloc_physrecs)
2627         cur_block_seclen = nb_alloc_physrecs;
2628
2629      fphysrecs += cur_block_seclen;
2630      win_file->fphysrecs = fphysrecs;
2631      /* TODO: update eldest FDR fphysrecs field */
2632      /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2633      nb_alloc_physrecs -= cur_block_seclen;
2634      if (! nb_alloc_physrecs)
2635         return 0;   /* done */
2636   }
2637
2638   /* find last non-empty cluster */
2639   for (cluster_index=0; (cluster_index<54) && (get_UINT16BE(win_file->curfdr.clusters[cluster_index][0]) != 0); cluster_index++)
2640      ;
2641   /* if we are dealing with an empty file, we will have (cluster_index == 0)... */
2642   if (cluster_index != 0)
2643   {
2644      cluster_index--;
2645      /* try to extend last cluster */
2646      /* point past cluster end */
2647      cluster_baseAU = get_UINT16BE(win_file->curfdr.clusters[cluster_index][1]) + 1;
2648      /* count free physrecs after last block */
2649      cur_block_seclen = 0;
2650      for (i=cluster_baseAU; (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7)))) && (cur_block_seclen < nb_alloc_physrecs) && (i < totAUs); i++)
2651         cur_block_seclen += win_file->l2_img->AUformat.physrecsperAU;
2652      if (cur_block_seclen)
2653      {   /* extend last block */
2654         if (cur_block_seclen > nb_alloc_physrecs)
2655            cur_block_seclen = nb_alloc_physrecs;
2656
2657         fphysrecs += cur_block_seclen;
2658         cluster_AUlen = (cur_block_seclen + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
2659         win_file->fphysrecs = fphysrecs;
2660         /* TODO: update eldest FDR fphysrecs field */
2661         /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2662         set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
2663                     get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
2664         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
2665                     get_UINT16BE(win_file->curfdr.clusters[cluster_index][1])+cluster_AUlen);
2666         for (i=0; i<cluster_AUlen; i++)
2667            win_file->l2_img->abm[(i+cluster_baseAU) >> 3] |= 1 << ((i+cluster_baseAU) & 7);
2668         nb_alloc_physrecs -= cur_block_seclen;
2669         if (! nb_alloc_physrecs)
2670            return 0;   /* done */
2671      }
2672      /* now point to first free entry in cluster table */
2673      cluster_index++;
2674   }
2675
2676   search_start = win_file->l2_img->data_offset;   /* initially, search for free space only in data space */
2677   while (nb_alloc_physrecs)
2678   {
2679      /* find smallest data block at least nb_alloc_physrecs in lenght, and largest data block less than nb_alloc_physrecs in lenght */
2680      first_best_block_seclen = INT_MAX;
2681      second_best_block_seclen = 0;
2682      for (i=search_start; i<totAUs; i++)
2683      {
2684         if (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2685         {   /* found one free block */
2686            /* compute its lenght */
2687            cluster_baseAU = i;
2688            cur_block_seclen = 0;
2689            while ((i<totAUs) && (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7)))))
2690            {
2691               cur_block_seclen += win_file->l2_img->AUformat.physrecsperAU;
2692               i++;
2693            }
2694            /* compare to previous best and second-best blocks */
2695            if ((cur_block_seclen < first_best_block_seclen) && (cur_block_seclen >= nb_alloc_physrecs))
2696            {
2697               first_best_block_baseAU = cluster_baseAU;
2698               first_best_block_seclen = cur_block_seclen;
2699               if (cur_block_seclen == nb_alloc_physrecs)
2700                  /* no need to search further */
2701                  break;
2702            }
2703            else if ((cur_block_seclen > second_best_block_seclen) && (cur_block_seclen < nb_alloc_physrecs))
2704            {
2705               second_best_block_baseAU = cluster_baseAU;
2706               second_best_block_seclen = cur_block_seclen;
2707            }
2708         }
2709      }
2710
2711      if ((first_best_block_seclen != INT_MAX) || (second_best_block_seclen != 0))
2712      {
2713         if (cluster_index == 54)
2714         {
2715            /* end of cluster list: go to next sibling FDR */
2716            if (write_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2717               return IMGTOOLERR_WRITEERROR;
2718            if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) != 0)
2719            {   /* read next sibling FDR */
2720               errorcode = win_goto_next_sibFDR(win_file);
2721               if (errorcode)
2722                  return errorcode;
2723            }
2724            else
2725            {   /* allocate new sibling FDR */
2726               errorcode = win_alloc_sibFDR(win_file);
2727               if (errorcode)
2728                  return errorcode;
2729            }
2730            cluster_index = 0;
2731         }
2732      }
2733
2734      if (first_best_block_seclen != INT_MAX)
2735      {   /* found one contiguous block which can hold it all */
2736         fphysrecs += nb_alloc_physrecs;
2737         cluster_AUlen = (nb_alloc_physrecs + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
2738         win_file->fphysrecs = fphysrecs;
2739         /* TODO: update eldest FDR fphysrecs field */
2740         /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2741         set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
2742                        get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
2743         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][0], first_best_block_baseAU);
2744         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
2745                        first_best_block_baseAU+cluster_AUlen-1);
2746
2747         for (i=0; i<cluster_AUlen; i++)
2748            win_file->l2_img->abm[(i+first_best_block_baseAU) >> 3] |= 1 << ((i+first_best_block_baseAU) & 7);
2749
2750         nb_alloc_physrecs = 0;
2751      }
2752      else if (second_best_block_seclen != 0)
2753      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
2754         fphysrecs += second_best_block_seclen;
2755         cluster_AUlen = (second_best_block_seclen + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
2756         win_file->fphysrecs = fphysrecs;
2757         /* TODO: update eldest FDR fphysrecs field */
2758         /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2759         set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
2760                        get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
2761         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][0], second_best_block_baseAU);
2762         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
2763                        second_best_block_baseAU+cluster_AUlen-1);
2764
2765         for (i=0; i<cluster_AUlen; i++)
2766            win_file->l2_img->abm[(i+second_best_block_baseAU) >> 3] |= 1 << ((i+second_best_block_baseAU) & 7);
2767
2768         nb_alloc_physrecs -= second_best_block_seclen;
2769
2770         /* now point to first free entry in cluster table */
2771         cluster_index++;
2772      }
2773      else if (search_start != 0)
2774      {   /* we did not find any free physrec in the data section of the disk */
2775         search_start = 0;   /* time to fall back to fdr space */
2776      }
2777      else
2778         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
2779   }
2780
2781   return 0;
2782}
2783
2784/*
2785   Allocate a new (empty) file
2786*/
2787static int new_file_lvl2_dsk(ti99_lvl2_imgref *l2_img, int parent_ref, char filename[10], ti99_lvl2_fileref *l2_file)
2788{
2789   ti99_catalog *catalog = &l2_img->u.dsk.catalogs[parent_ref];
2790   unsigned fdr_AU, fdr_aphysrec;
2791   int catalog_index, i;
2792   int reply = 0;
2793   int errorcode;
2794
2795
2796   if (catalog->num_files >= 127)
2797      /* if num_files == 128, catalog is full */
2798      /* if num_files == 127, catalog is not full, but we don't want to write
2799      a 128th entry for compatibility with some existing DSRs that detect the
2800      end of the FDIR array with a 0 entry (and do not check that the index
2801      has not reached 128) */
2802      return IMGTOOLERR_NOSPACE;
2803
2804   /* find insertion point in catalog */
2805   for (i=0; (i < catalog->num_files) && ((reply = memcmp(catalog->files[i].name, filename, 10)) < 0); i++)
2806      ;
2807
2808   if ((i<catalog->num_files) && (reply == 0))
2809      /* file already exists */
2810      return IMGTOOLERR_BADFILENAME;
2811   else
2812   {
2813      /* otherwise insert new entry */
2814      catalog_index = i;
2815      errorcode = alloc_fdr_AU(l2_img, &fdr_AU);
2816      if (errorcode)
2817         return errorcode;
2818      fdr_aphysrec = fdr_AU * l2_img->AUformat.physrecsperAU;
2819
2820      /* shift catalog entries until the insertion point */
2821      for (i=catalog->num_files; i>catalog_index; i--)
2822         catalog->files[i] = catalog->files[i-1];
2823
2824      /* write new catalog entry */
2825      catalog->files[catalog_index].fdr_ptr = fdr_aphysrec;
2826      memcpy(catalog->files[catalog_index].name, filename, 10);
2827
2828      /* update catalog len */
2829      catalog->num_files++;
2830   }
2831
2832   /* set up file handle */
2833   l2_file->type = L2F_DSK;
2834   l2_file->u.dsk.l2_img = l2_img;
2835   l2_file->u.dsk.fdr_aphysrec = fdr_aphysrec;
2836   memset(&l2_file->u.dsk.fdr, 0, sizeof(l2_file->u.dsk.fdr));
2837   memcpy(l2_file->u.dsk.fdr.name, filename, 10);
2838
2839   return 0;
2840}
2841
2842/*
2843   Allocate a new (empty) file
2844*/
2845static int new_file_lvl2_win(ti99_lvl2_imgref *l2_img, ti99_catalog *parent_catalog, char filename[10], ti99_lvl2_fileref *l2_file)
2846{
2847   unsigned fdr_AU;
2848   int catalog_index, i;
2849   int reply = 0;
2850   int errorcode;
2851
2852
2853   if (parent_catalog->num_files >= 127)
2854      /* if num_files == 127, catalog is full */
2855      return IMGTOOLERR_NOSPACE;
2856
2857   /* find insertion point in catalog */
2858   for (i=0; (i < parent_catalog->num_files) && ((reply = memcmp(parent_catalog->files[i].name, filename, 10)) < 0); i++)
2859      ;
2860
2861   if ((i<parent_catalog->num_files) && (reply == 0))
2862      /* file already exists */
2863      return IMGTOOLERR_BADFILENAME;
2864   else
2865   {
2866      /* otherwise insert new entry */
2867      catalog_index = i;
2868      errorcode = alloc_fdr_AU(l2_img, &fdr_AU);
2869      if (errorcode)
2870         return errorcode;
2871
2872      /* shift catalog entries until the insertion point */
2873      for (i=parent_catalog->num_files; i>catalog_index; i--)
2874         parent_catalog->files[i] = parent_catalog->files[i-1];
2875
2876      /* write new catalog entry */
2877      parent_catalog->files[catalog_index].fdr_ptr = fdr_AU;
2878      memcpy(parent_catalog->files[catalog_index].name, filename, 10);
2879
2880      /* update catalog len */
2881      parent_catalog->num_files++;
2882   }
2883
2884   /* set up file handle */
2885   l2_file->type = L2F_WIN;
2886   l2_file->u.win.l2_img = l2_img;
2887   l2_file->u.win.fphysrecs = 0;
2888   l2_file->u.win.eldestfdr_aphysrec = fdr_AU * l2_img->AUformat.physrecsperAU;
2889   l2_file->u.win.curfdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
2890   memset(&l2_file->u.win.curfdr, 0, sizeof(l2_file->u.win.curfdr));
2891   memcpy(l2_file->u.win.curfdr.name, filename, 10);
2892
2893   return 0;
2894}
2895
2896/*
2897   Allocate a new (empty) file
2898*/
2899static int new_file_lvl2_tifiles(imgtool_stream *file_handle, ti99_lvl2_fileref *l2_file)
2900{
2901   /* set up file handle */
2902   l2_file->type = L2F_TIFILES;
2903   l2_file->u.tifiles.file_handle = file_handle;
2904   memset(&l2_file->u.tifiles.hdr, 0, sizeof(l2_file->u.tifiles.hdr));
2905   l2_file->u.tifiles.hdr.tifiles[0] = '\7';
2906   l2_file->u.tifiles.hdr.tifiles[1] = 'T';
2907   l2_file->u.tifiles.hdr.tifiles[2] = 'I';
2908   l2_file->u.tifiles.hdr.tifiles[3] = 'F';
2909   l2_file->u.tifiles.hdr.tifiles[4] = 'I';
2910   l2_file->u.tifiles.hdr.tifiles[5] = 'L';
2911   l2_file->u.tifiles.hdr.tifiles[6] = 'E';
2912   l2_file->u.tifiles.hdr.tifiles[7] = 'S';
2913
2914   return 0;
2915}
2916
2917/*
2918   Open an existing file on a floppy image
2919
2920   l2_img: level 2 image the file is located on
2921   fpath: access path to the file
2922   file: set up if open is successful
2923*/
2924static int open_file_lvl2_dsk(ti99_lvl2_imgref *l2_img, const char *fpath, ti99_lvl2_fileref *l2_file)
2925{
2926   int parent_ref, is_dir, catalog_index;
2927   int reply;
2928
2929
2930   reply = dsk_find_catalog_entry(l2_img, fpath, NULL, &parent_ref, &is_dir, &catalog_index);
2931   if (reply)
2932      return reply;
2933
2934   if (is_dir)
2935      /* this is not a file */
2936      return IMGTOOLERR_BADFILENAME;
2937
2938   l2_file->type = L2F_DSK;
2939   l2_file->u.dsk.l2_img = l2_img;
2940   l2_file->u.dsk.fdr_aphysrec = l2_img->u.dsk.catalogs[parent_ref].files[catalog_index].fdr_ptr;
2941   if (read_absolute_physrec(& l2_img->l1_img, l2_file->u.dsk.fdr_aphysrec, &l2_file->u.dsk.fdr))
2942      return IMGTOOLERR_READERROR;
2943
2944   return 0;
2945}
2946
2947/*
2948   Open an existing file on a harddisk image
2949
2950   l2_img: level 2 image the file is located on
2951   fpath: access path to the file
2952   file: set up if open is successful
2953*/
2954static int open_file_lvl2_win(ti99_lvl2_imgref *l2_img, const char *fpath, ti99_lvl2_fileref *l2_file)
2955{
2956   int parent_ref, is_dir, catalog_index;
2957   ti99_catalog catalog;
2958   int reply;
2959
2960   reply = win_find_catalog_entry(l2_img, fpath, NULL, &parent_ref, &catalog, &is_dir, &catalog_index);
2961   if (reply)
2962      return reply;
2963
2964   if (is_dir)
2965      /* this is not a file */
2966      return IMGTOOLERR_BADFILENAME;
2967
2968   l2_file->type = L2F_WIN;
2969   l2_file->u.win.l2_img = l2_img;
2970   l2_file->u.win.eldestfdr_aphysrec = catalog.files[catalog_index].fdr_ptr * l2_img->AUformat.physrecsperAU;
2971   l2_file->u.win.curfdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
2972   if (read_absolute_physrec(& l2_img->l1_img, l2_file->u.win.curfdr_aphysrec, &l2_file->u.win.curfdr))
2973      return IMGTOOLERR_READERROR;
2974   l2_file->u.win.fphysrecs = get_win_fdr_fphysrecs(&l2_file->u.win.curfdr);
2975
2976   /* check integrity of FDR sibling chain */
2977   /* note that as we check that the back chain is consistent with the forward
2978   chain, we will also detect any cycle in the sibling chain, so we do not
2979   need to check against them explicitely */
2980   if (get_UINT16BE(l2_file->u.win.curfdr.prevsibFDR_AU) != 0)
2981      return IMGTOOLERR_CORRUPTIMAGE;
2982
2983   {
2984      int i, pastendoflist_flag;
2985      unsigned cur_fphysrec, sibFDR_AUlen;
2986      win_fdr *cur_fdr, fdr_buf;
2987      unsigned curfdr_aphysrec, prevfdr_aphysrec;
2988
2989      cur_fphysrec = 0;
2990      pastendoflist_flag = 0;
2991      cur_fdr = &l2_file->u.win.curfdr;
2992      curfdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
2993
2994      while (1)
2995      {
2996         sibFDR_AUlen = 0;
2997         i=0;
2998         if (! pastendoflist_flag)
2999         {
3000            /* compute number of allocated AUs and check number of AUs */
3001            for (; i<54; i++)
3002            {
3003               if (get_UINT16BE(cur_fdr->clusters[i][0]) == 0)
3004               {
3005                  pastendoflist_flag = TRUE;
3006                  break;
3007               }
3008               sibFDR_AUlen += get_UINT16BE(cur_fdr->clusters[i][1])
3009                           - get_UINT16BE(cur_fdr->clusters[i][0])
3010                           + 1;
3011            }
3012         }
3013         /* clear remainder of cluster table */
3014         for (; i<54; i++)
3015         {
3016            /*set_UINT16BE(&cur_fdr->clusters[i][0], 0);
3017            set_UINT16BE(&cur_fdr->clusters[i][1], 0);*/
3018            if ((get_UINT16BE(cur_fdr->clusters[i][0]) != 0) || (get_UINT16BE(cur_fdr->clusters[i][1]) != 0))
3019               return IMGTOOLERR_CORRUPTIMAGE;
3020         }
3021
3022         /* check sibFDR_AUlen field */
3023         if (get_UINT16BE(cur_fdr->sibFDR_AUlen) != sibFDR_AUlen)
3024            return IMGTOOLERR_CORRUPTIMAGE;
3025
3026         /* update current file physrec position to point to end of sibling FDR */
3027         cur_fphysrec += sibFDR_AUlen * l2_file->u.win.l2_img->AUformat.physrecsperAU;
3028
3029         /* exit loop if end of sibling chain */
3030         if (! get_UINT16BE(cur_fdr->nextsibFDR_AU))
3031            break;
3032
3033         /* otherwise read next FDR */
3034         if (get_UINT16BE(cur_fdr->nextsibFDR_AU) >= l2_file->u.win.l2_img->AUformat.totAUs)
3035            return IMGTOOLERR_CORRUPTIMAGE;
3036
3037         prevfdr_aphysrec = curfdr_aphysrec;
3038         curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(l2_file->u.win.l2_img, cur_fdr);
3039         if (read_absolute_physrec(& l2_file->u.win.l2_img->l1_img, curfdr_aphysrec, &fdr_buf))
3040            return IMGTOOLERR_READERROR;
3041         cur_fdr = &fdr_buf;
3042
3043         /* check that back chaining is consistent with forward chaining */
3044         if (get_win_fdr_prevsibFDR_aphysrec(l2_file->u.win.l2_img, &fdr_buf) != prevfdr_aphysrec)
3045            return IMGTOOLERR_CORRUPTIMAGE;
3046         /*  check fphysrecs field */
3047         if (get_win_fdr_fphysrecs(&fdr_buf) != cur_fphysrec)
3048            return IMGTOOLERR_CORRUPTIMAGE;
3049
3050         /* check consistency of informative fields (name, record format, flags, etc) */
3051         if (memcmp(fdr_buf.name, l2_file->u.win.curfdr.name, 10)
3052               || (get_UINT16BE(fdr_buf.xreclen) != get_UINT16BE(l2_file->u.win.curfdr.xreclen))
3053               || (fdr_buf.flags != l2_file->u.win.curfdr.flags)
3054               || (fdr_buf.recsperphysrec != l2_file->u.win.curfdr.recsperphysrec)
3055               || (fdr_buf.eof != l2_file->u.win.curfdr.eof)
3056               || (fdr_buf.reclen != l2_file->u.win.curfdr.reclen)
3057               || (get_UINT16LE(fdr_buf.fixrecs_LSW) != get_UINT16LE(l2_file->u.win.curfdr.fixrecs_LSW))
3058               || memcmp(&fdr_buf.creation, &l2_file->u.win.curfdr.creation, 4)
3059               || memcmp(&fdr_buf.update, &l2_file->u.win.curfdr.update, 4)
3060               /*|| memcmp(fdr_buf.id, l2_file->u.win.curfdr.id, 2)*/
3061               || (get_UINT16BE(fdr_buf.parent_FDIR_AU) != get_UINT16BE(l2_file->u.win.curfdr.parent_FDIR_AU))
3062               || ((fdr_buf.xinfo_MSB & 0xf) != (l2_file->u.win.curfdr.xinfo_MSB & 0xf)))
3063            return IMGTOOLERR_CORRUPTIMAGE;
3064      }
3065      if (cur_fphysrec < l2_file->u.win.fphysrecs)
3066         return IMGTOOLERR_CORRUPTIMAGE;
3067   }
3068
3069   return 0;
3070}
3071
3072/*
3073   Open an existing file in TIFILES format
3074*/
3075static int open_file_lvl2_tifiles(imgtool_stream *file_handle, ti99_lvl2_fileref *l2_file)
3076{
3077   /* set up file handle */
3078   l2_file->type = L2F_TIFILES;
3079   l2_file->u.tifiles.file_handle = file_handle;
3080
3081   /* seek to header */
3082   if (stream_seek(l2_file->u.tifiles.file_handle, 0, SEEK_SET))
3083      return IMGTOOLERR_READERROR;
3084   /* read it */
3085   if (stream_read(l2_file->u.tifiles.file_handle, &l2_file->u.tifiles.hdr, sizeof(l2_file->u.tifiles.hdr)) != sizeof(l2_file->u.tifiles.hdr))
3086      return IMGTOOLERR_READERROR;
3087
3088   return 0;
3089}
3090
3091/*
3092   compute the aphysrec address for a given file physical record (fphysrec)
3093
3094   l2_img: image where the file is located
3095*/
3096static int dsk_fphysrec_to_aphysrec(ti99_lvl2_fileref_dsk *dsk_file, unsigned fphysrec, unsigned *aphysrec)
3097{
3098   int cluster_index;
3099   int cluster_firstfphysrec, cluster_lastfphysrec;
3100   int cluster_baseaphysrec;
3101
3102
3103   /* check parameter */
3104   if (fphysrec >= get_UINT16BE(dsk_file->fdr.fphysrecs))
3105      return IMGTOOLERR_UNEXPECTED;
3106
3107
3108   /* search for the cluster in the data chain pointers array */
3109   cluster_firstfphysrec = 0;
3110   for (cluster_index=0; cluster_index<76; cluster_index++)
3111   {
3112      /* read curent file block table entry */
3113      cluster_lastfphysrec = get_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index);
3114      if (cluster_lastfphysrec >= fphysrec)
3115         break;
3116      cluster_firstfphysrec = cluster_lastfphysrec+1;
3117   }
3118   if (cluster_index == 76)
3119      /* if not found, the file is corrupt */
3120      return IMGTOOLERR_CORRUPTIMAGE;
3121
3122   /* read base aphysrec address for this cluster */
3123   cluster_baseaphysrec = get_dsk_fdr_cluster_baseaphysrec(dsk_file->l2_img, &dsk_file->fdr, cluster_index);
3124   /* return absolute physrec address */
3125   *aphysrec = cluster_baseaphysrec + (fphysrec - cluster_firstfphysrec);
3126   return 0;
3127}
3128
3129/*
3130   compute the aphysrec address for a given file physical record (fphysrec)
3131
3132   l2_img: image where the file is located
3133*/
3134static int win_fphysrec_to_aphysrec(ti99_lvl2_fileref_win *win_file, unsigned fphysrec, unsigned *aphysrec)
3135{
3136   int cluster_index;
3137   int cluster_firstfphysrec, cluster_lastfphysrec;
3138   int cluster_baseaphysrec;
3139   int errorcode;
3140
3141
3142   /* check parameter */
3143   if (fphysrec >= win_file->fphysrecs)
3144      return IMGTOOLERR_UNEXPECTED;
3145
3146   /* look for correct sibling */
3147   if (fphysrec < get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr))
3148   {
3149      while (fphysrec < get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr))
3150      {
3151         if (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) == 0)
3152            return IMGTOOLERR_CORRUPTIMAGE;
3153         errorcode = win_goto_prev_sibFDR(win_file);
3154         if (errorcode)
3155            return errorcode;
3156      }
3157   }
3158   else /*if (fphysrec >= get_win_fdr_cursibFDR_basefphysrec(& dsk_file->curfdr))*/
3159   {
3160      while (fphysrec >= (get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr)
3161                        + get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU))
3162      {
3163         if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) == 0)
3164            return IMGTOOLERR_CORRUPTIMAGE;
3165         errorcode = win_goto_next_sibFDR(win_file);
3166         if (errorcode)
3167            return errorcode;
3168      }
3169   }
3170
3171
3172   /* search for the cluster in the data chain pointers array */
3173   cluster_firstfphysrec = get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr);
3174   for (cluster_index = 0; cluster_index<54; cluster_index++)
3175   {
3176      cluster_lastfphysrec = cluster_firstfphysrec
3177                           + (get_UINT16BE(win_file->curfdr.clusters[cluster_index][1])
3178                                 - get_UINT16BE(win_file->curfdr.clusters[cluster_index][0])
3179                                 + 1)
3180                              * win_file->l2_img->AUformat.physrecsperAU;
3181      if (fphysrec < cluster_lastfphysrec)
3182         break;
3183
3184      cluster_firstfphysrec = cluster_lastfphysrec;
3185   }
3186
3187   if (cluster_index == 54)
3188      return IMGTOOLERR_CORRUPTIMAGE;
3189
3190
3191   /* read base aphysrec address for this cluster */
3192   cluster_baseaphysrec = get_UINT16BE(win_file->curfdr.clusters[cluster_index][0]) * win_file->l2_img->AUformat.physrecsperAU;
3193   /* return absolute physrec address */
3194   *aphysrec = cluster_baseaphysrec + (fphysrec - cluster_firstfphysrec);
3195   return 0;
3196}
3197
3198/*
3199   read a 256-byte physical record from a file
3200*/
3201static int read_file_physrec(ti99_lvl2_fileref *l2_file, unsigned fphysrec, void *dest)
3202{
3203   int errorcode;
3204   unsigned aphysrec;
3205
3206   switch (l2_file->type)
3207   {
3208   case L2F_DSK:
3209      /* compute absolute physrec address */
3210      errorcode = dsk_fphysrec_to_aphysrec(&l2_file->u.dsk, fphysrec, &aphysrec);
3211      if (errorcode)
3212         return errorcode;
3213      /* read physrec */
3214      if (read_absolute_physrec(& l2_file->u.dsk.l2_img->l1_img, aphysrec, dest))
3215         return IMGTOOLERR_READERROR;
3216      break;
3217
3218   case L2F_WIN:
3219      /* compute absolute physrec address */
3220      errorcode = win_fphysrec_to_aphysrec(&l2_file->u.win, fphysrec, &aphysrec);
3221      if (errorcode)
3222         return errorcode;
3223      /* read physrec */
3224      if (read_absolute_physrec(& l2_file->u.win.l2_img->l1_img, aphysrec, dest))
3225         return IMGTOOLERR_READERROR;
3226      break;
3227
3228   case L2F_TIFILES:
3229      /* seek to physrec */
3230      if (stream_seek(l2_file->u.tifiles.file_handle, 128+256*fphysrec, SEEK_SET))
3231         return IMGTOOLERR_READERROR;
3232      /* read it */
3233      if (stream_read(l2_file->u.tifiles.file_handle, dest, 256) != 256)
3234         return IMGTOOLERR_READERROR;
3235      break;
3236   }
3237
3238   return 0;
3239}
3240
3241/*
3242   read a 256-byte physical record from a file
3243*/
3244static int write_file_physrec(ti99_lvl2_fileref *l2_file, unsigned fphysrec, const void *src)
3245{
3246   int errorcode;
3247   unsigned aphysrec;
3248
3249   switch (l2_file->type)
3250   {
3251   case L2F_DSK:
3252      /* compute absolute physrec address */
3253      errorcode = dsk_fphysrec_to_aphysrec(&l2_file->u.dsk, fphysrec, &aphysrec);
3254      if (errorcode)
3255         return errorcode;
3256      /* write physrec */
3257      if (write_absolute_physrec(& l2_file->u.dsk.l2_img->l1_img, aphysrec, src))
3258         return IMGTOOLERR_WRITEERROR;
3259      break;
3260
3261   case L2F_WIN:
3262      /* compute absolute physrec address */
3263      errorcode = win_fphysrec_to_aphysrec(&l2_file->u.win, fphysrec, &aphysrec);
3264      if (errorcode)
3265         return errorcode;
3266      /* write physrec */
3267      if (write_absolute_physrec(& l2_file->u.win.l2_img->l1_img, aphysrec, src))
3268         return IMGTOOLERR_WRITEERROR;
3269      break;
3270
3271   case L2F_TIFILES:
3272      /* seek to physrec */
3273      if (stream_seek(l2_file->u.tifiles.file_handle, 128+256*fphysrec, SEEK_SET))
3274         return IMGTOOLERR_WRITEERROR;
3275      /* write it */
3276      if (stream_write(l2_file->u.tifiles.file_handle, src, 256) != 256)
3277         return IMGTOOLERR_WRITEERROR;
3278      break;
3279   }
3280
3281   return 0;
3282}
3283
3284/*
3285   Write a field in every fdr record associated to a file
3286*/
3287/*static int set_win_fdr_field(ti99_lvl2_fileref *l2_file, size_t offset, size_t size, void *data)
3288{
3289   win_fdr fdr_buf;
3290   unsigned fdr_aphysrec;
3291   int errorcode = 0;
3292
3293   for (fdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
3294         fdr_aphysrec && ((errorcode = (read_absolute_physrec(&l2_file->u.win.l2_img->l1_img, fdr_aphysrec, &fdr_buf) ? IMGTOOLERR_READERROR : 0)) == 0);
3295         fdr_aphysrec = get_win_fdr_nextsibFDR_physrec(l2_file->u.win.l2_img, &fdr_buf))
3296   {
3297      memcpy(((UINT8 *) &fdr_buf) + offset, data, size);
3298      if (write_absolute_physrec(&l2_file->u.win.l2_img->l1_img, fdr_aphysrec, &fdr_buf))
3299      {
3300         errorcode = IMGTOOLERR_WRITEERROR;
3301         break;
3302      }
3303   }
3304
3305   return errorcode;
3306}*/
3307
3308static UINT8 get_file_flags(ti99_lvl2_fileref *l2_file)
3309{
3310   int reply = 0;
3311
3312   switch (l2_file->type)
3313   {
3314   case L2F_DSK:
3315      reply = l2_file->u.dsk.fdr.flags;
3316      break;
3317
3318   case L2F_WIN:
3319      reply = l2_file->u.win.curfdr.flags;
3320      break;
3321
3322   case L2F_TIFILES:
3323      reply = l2_file->u.tifiles.hdr.flags;
3324      break;
3325   }
3326
3327   return reply;
3328}
3329
3330static void set_file_flags(ti99_lvl2_fileref *l2_file, UINT8 data)
3331{
3332   switch (l2_file->type)
3333   {
3334   case L2F_DSK:
3335      l2_file->u.dsk.fdr.flags = data;
3336      break;
3337
3338   case L2F_WIN:
3339      l2_file->u.win.curfdr.flags = data;
3340      break;
3341
3342   case L2F_TIFILES:
3343      l2_file->u.tifiles.hdr.flags = data;
3344      break;
3345   }
3346}
3347
3348static UINT8 get_file_recsperphysrec(ti99_lvl2_fileref *l2_file)
3349{
3350   int reply = 0;
3351
3352   switch (l2_file->type)
3353   {
3354   case L2F_DSK:
3355      reply = l2_file->u.dsk.fdr.recsperphysrec;
3356      break;
3357
3358   case L2F_WIN:
3359      reply = l2_file->u.win.curfdr.recsperphysrec;
3360      break;
3361
3362   case L2F_TIFILES:
3363      reply = l2_file->u.tifiles.hdr.recsperphysrec;
3364      break;
3365   }
3366
3367   return reply;
3368}
3369
3370static void set_file_recsperphysrec(ti99_lvl2_fileref *l2_file, UINT8 data)
3371{
3372   switch (l2_file->type)
3373   {
3374   case L2F_DSK:
3375      l2_file->u.dsk.fdr.recsperphysrec = data;
3376      break;
3377
3378   case L2F_WIN:
3379      l2_file->u.win.curfdr.recsperphysrec = data;
3380      break;
3381
3382   case L2F_TIFILES:
3383      l2_file->u.tifiles.hdr.recsperphysrec = data;
3384      break;
3385   }
3386}
3387
3388static unsigned get_file_fphysrecs(ti99_lvl2_fileref *l2_file)
3389{
3390   int reply = 0;
3391
3392   switch (l2_file->type)
3393   {
3394   case L2F_DSK:
3395      reply = get_UINT16BE(l2_file->u.dsk.fdr.fphysrecs);
3396      break;
3397
3398   case L2F_WIN:
3399      reply = l2_file->u.win.fphysrecs;
3400      break;
3401
3402   case L2F_TIFILES:
3403      reply = get_UINT16BE(l2_file->u.tifiles.hdr.fphysrecs);
3404      break;
3405   }
3406
3407   return reply;
3408}
3409
3410static int set_file_fphysrecs(ti99_lvl2_fileref *l2_file, unsigned data)
3411{
3412   switch (l2_file->type)
3413   {
3414   case L2F_DSK:
3415      if (data >= 65536)
3416         return IMGTOOLERR_UNIMPLEMENTED;
3417      set_UINT16BE(&l2_file->u.dsk.fdr.fphysrecs, data);
3418      break;
3419
3420   case L2F_WIN:
3421      l2_file->u.win.fphysrecs = data;
3422      break;
3423
3424   case L2F_TIFILES:
3425      if (data >= 65536)
3426         return IMGTOOLERR_UNIMPLEMENTED;
3427      set_UINT16BE(&l2_file->u.tifiles.hdr.fphysrecs, data);
3428      break;
3429   }
3430
3431   return 0;
3432}
3433
3434static UINT8 get_file_eof(ti99_lvl2_fileref *l2_file)
3435{
3436   int reply = 0;
3437
3438   switch (l2_file->type)
3439   {
3440   case L2F_DSK:
3441      reply = l2_file->u.dsk.fdr.eof;
3442      break;
3443
3444   case L2F_WIN:
3445      reply = l2_file->u.win.curfdr.eof;
3446      break;
3447
3448   case L2F_TIFILES:
3449      reply = l2_file->u.tifiles.hdr.eof;
3450      break;
3451   }
3452
3453   return reply;
3454}
3455
3456static void set_file_eof(ti99_lvl2_fileref *l2_file, UINT8 data)
3457{
3458   switch (l2_file->type)
3459   {
3460   case L2F_DSK:
3461      l2_file->u.dsk.fdr.eof = data;
3462      break;
3463
3464   case L2F_WIN:
3465      l2_file->u.win.curfdr.eof = data;
3466      break;
3467
3468   case L2F_TIFILES:
3469      l2_file->u.tifiles.hdr.eof = data;
3470      break;
3471   }
3472}
3473
3474static UINT16 get_file_reclen(ti99_lvl2_fileref *l2_file)
3475{
3476   int reply = 0;
3477
3478   switch (l2_file->type)
3479   {
3480   case L2F_DSK:
3481      reply = l2_file->u.dsk.fdr.reclen;
3482      if ((reply == 0) && (! (l2_file->u.dsk.fdr.flags & (fdr99_f_program /*| fdr99_f_var*/))))
3483         reply = get_UINT16BE(l2_file->u.dsk.fdr.xreclen);
3484      break;
3485
3486   case L2F_WIN:
3487      reply = l2_file->u.win.curfdr.reclen;
3488      if ((reply == 0) && (! (l2_file->u.win.curfdr.flags & (fdr99_f_program /*| fdr99_f_var*/))))
3489         reply = get_UINT16BE(l2_file->u.win.curfdr.xreclen);
3490      break;
3491
3492   case L2F_TIFILES:
3493      reply = l2_file->u.tifiles.hdr.reclen;
3494      break;
3495   }
3496
3497   return reply;
3498}
3499
3500static int set_file_reclen(ti99_lvl2_fileref *l2_file, UINT16 data)
3501{
3502   switch (l2_file->type)
3503   {
3504   case L2F_DSK:
3505      if (data < 256)
3506      {
3507         l2_file->u.dsk.fdr.reclen = data;
3508         set_UINT16BE(&l2_file->u.dsk.fdr.xreclen, 0);
3509      }
3510      else
3511      {
3512         l2_file->u.dsk.fdr.reclen = 0;
3513         set_UINT16BE(&l2_file->u.dsk.fdr.xreclen, data);
3514      }
3515      break;
3516
3517   case L2F_WIN:
3518      if (data < 256)
3519      {
3520         l2_file->u.win.curfdr.reclen = data;
3521         set_UINT16BE(&l2_file->u.win.curfdr.xreclen, 0);
3522      }
3523      else
3524      {
3525         l2_file->u.win.curfdr.reclen = 0;
3526         set_UINT16BE(&l2_file->u.win.curfdr.xreclen, data);
3527      }
3528      break;
3529
3530   case L2F_TIFILES:
3531      if (data >= 256)
3532         return IMGTOOLERR_UNIMPLEMENTED;
3533      l2_file->u.tifiles.hdr.reclen = data;
3534      break;
3535   }
3536
3537   return 0;
3538}
3539
3540static unsigned get_file_fixrecs(ti99_lvl2_fileref *l2_file)
3541{
3542   int reply = 0;
3543
3544   switch (l2_file->type)
3545   {
3546   case L2F_DSK:
3547      reply = get_UINT16LE(l2_file->u.dsk.fdr.fixrecs);
3548      break;
3549
3550   case L2F_WIN:
3551      reply = get_win_fdr_fixrecs(&l2_file->u.win.curfdr);
3552      break;
3553
3554   case L2F_TIFILES:
3555      reply = get_UINT16BE(l2_file->u.tifiles.hdr.fixrecs);
3556      break;
3557   }
3558
3559   return reply;
3560}
3561
3562static int set_file_fixrecs(ti99_lvl2_fileref *l2_file, unsigned data)
3563{
3564   switch (l2_file->type)
3565   {
3566   case L2F_DSK:
3567      if (data >= 65536)
3568         return IMGTOOLERR_UNIMPLEMENTED;
3569      set_UINT16LE(&l2_file->u.dsk.fdr.fixrecs, data);
3570      break;
3571
3572   case L2F_WIN:
3573      set_win_fdr_fixrecs(&l2_file->u.win.curfdr, data);
3574      break;
3575
3576   case L2F_TIFILES:
3577      if (data >= 65536)
3578         return IMGTOOLERR_UNIMPLEMENTED;
3579      set_UINT16BE(&l2_file->u.tifiles.hdr.fixrecs, data);
3580      break;
3581   }
3582
3583   return 0;
3584}
3585
3586static void get_file_creation_date(ti99_lvl2_fileref *l2_file, ti99_date_time *reply)
3587{
3588   switch (l2_file->type)
3589   {
3590   case L2F_DSK:
3591      *reply = l2_file->u.dsk.fdr.creation;
3592      break;
3593
3594   case L2F_WIN:
3595      *reply = l2_file->u.win.curfdr.creation;
3596      break;
3597
3598   case L2F_TIFILES:
3599      memset(reply, 0, sizeof(*reply));
3600      break;
3601   }
3602}
3603
3604static void set_file_creation_date(ti99_lvl2_fileref *l2_file, ti99_date_time data)
3605{
3606   switch (l2_file->type)
3607   {
3608   case L2F_DSK:
3609      l2_file->u.dsk.fdr.creation = data;
3610      break;
3611
3612   case L2F_WIN:
3613      l2_file->u.win.curfdr.creation = data;
3614      break;
3615
3616   case L2F_TIFILES:
3617      break;
3618   }
3619}
3620
3621static void get_file_update_date(ti99_lvl2_fileref *l2_file, ti99_date_time *reply)
3622{
3623   switch (l2_file->type)
3624   {
3625   case L2F_DSK:
3626      *reply = l2_file->u.dsk.fdr.update;
3627      break;
3628
3629   case L2F_WIN:
3630      *reply = l2_file->u.win.curfdr.update;
3631      break;
3632
3633   case L2F_TIFILES:
3634      memset(reply, 0, sizeof(*reply));
3635      break;
3636   }
3637}
3638
3639static void set_file_update_date(ti99_lvl2_fileref *l2_file, ti99_date_time data)
3640{
3641   switch (l2_file->type)
3642   {
3643   case L2F_DSK:
3644      l2_file->u.dsk.fdr.update = data;
3645      break;
3646
3647   case L2F_WIN:
3648      l2_file->u.win.curfdr.update = data;
3649      break;
3650
3651   case L2F_TIFILES:
3652      break;
3653   }
3654}
3655
3656#ifdef UNUSED_FUNCTION
3657static void current_date_time(ti99_date_time *reply)
3658{
3659   /* All these functions should be ANSI */
3660   time_t cur_time = time(NULL);
3661   struct tm expanded_time = *localtime(& cur_time);
3662
3663   reply->time_MSB = (expanded_time.tm_hour << 3) | (expanded_time.tm_min >> 3);
3664   reply->time_LSB = (expanded_time.tm_min << 5) | (expanded_time.tm_sec >> 1);
3665   reply->date_MSB = ((expanded_time.tm_year % 100) << 1) | ((expanded_time.tm_mon+1) >> 3);
3666   reply->date_LSB = ((expanded_time.tm_mon+1) << 5) | expanded_time.tm_mday;
3667}
3668#endif
3669
3670#if 0
3671#pragma mark -
3672#pragma mark LEVEL 3 DISK ROUTINES
3673#endif
3674
3675/*
3676   Level 3 implements files as a succession of logical records.
3677
3678   There are three types of files:
3679   * program files that are not implemented at level 3 (no logical record)
3680   * files with fixed-size records (random-access files)
3681   * files with variable-size records (sequential-access)
3682*/
3683
3684typedef struct ti99_lvl3_fileref
3685{
3686   ti99_lvl2_fileref l2_file;
3687
3688   int cur_log_rec;
3689   int cur_phys_rec;
3690   int cur_pos_in_phys_rec;
3691} ti99_lvl3_fileref;
3692
3693#ifdef UNUSED_FUNCTION
3694/*
3695   Open a file on level 3.
3696
3697   To open a file on level 3, you must open (or create) the file on level 2,
3698   then pass the file reference to open_file_lvl3.
3699*/
3700static int open_file_lvl3(ti99_lvl3_fileref *l3_file)
3701{
3702   l3_file->cur_log_rec = 0;
3703   l3_file->cur_phys_rec = 0;
3704   l3_file->cur_pos_in_phys_rec = 0;
3705
3706   /*if ()*/
3707
3708   return 0;
3709}
3710
3711/*
3712   Test a file for EOF
3713*/
3714static int is_eof(ti99_lvl3_fileref *l3_file)
3715{
3716   int flags = get_file_flags(&l3_file->l2_file);
3717   int fphysrecs = get_file_fphysrecs(&l3_file->l2_file);
3718   int fdr_eof = get_file_eof(&l3_file->l2_file);
3719
3720   if (flags & fdr99_f_var)
3721   {
3722      return (l3_file->cur_phys_rec >= fphysrecs);
3723   }
3724   else
3725   {
3726      return ((l3_file->cur_phys_rec >= fphysrecs)
3727            || ((l3_file->cur_phys_rec == (fphysrecs-1))
3728               && (l3_file->cur_pos_in_phys_rec >= (fdr_eof ? fdr_eof : 256))));
3729   }
3730}
3731
3732/*
3733   Read next record from a file
3734*/
3735static int read_next_record(ti99_lvl3_fileref *l3_file, void *dest, int *out_reclen)
3736{
3737   int errorcode;
3738   UINT8 physrec_buf[256];
3739   int reclen;
3740   int flags = get_file_flags(&l3_file->l2_file);
3741   int fphysrecs = get_file_fphysrecs(&l3_file->l2_file);
3742   int fdr_eof = get_file_eof(&l3_file->l2_file);
3743
3744   if (flags & fdr99_f_program)
3745   {
3746      /* program files have no level-3 record */
3747      return IMGTOOLERR_UNEXPECTED;
3748   }
3749   else if (flags & fdr99_f_var)
3750   {
3751      /* variable-lenght records */
3752      if (is_eof(l3_file))
3753         return IMGTOOLERR_UNEXPECTED;
3754      errorcode = read_file_physrec(&l3_file->l2_file, l3_file->cur_phys_rec, physrec_buf);
3755      if (errorcode)
3756         return errorcode;
3757      /* read reclen */
3758      reclen = physrec_buf[l3_file->cur_pos_in_phys_rec];
3759      /* check integrity */
3760      if ((reclen == 0xff) || (reclen > get_file_reclen(&l3_file->l2_file))
3761            || ((l3_file->cur_pos_in_phys_rec + 1 + reclen) > 256))
3762         return IMGTOOLERR_CORRUPTIMAGE;
3763      /* copy to buffer */
3764      memcpy(dest, physrec_buf + l3_file->cur_pos_in_phys_rec + 1, reclen);
3765      l3_file->cur_pos_in_phys_rec += reclen + 1;
3766      /* skip to next physrec if needed */
3767      if ((l3_file->cur_pos_in_phys_rec == 256)
3768            || (physrec_buf[l3_file->cur_pos_in_phys_rec] == 0xff))
3769      {
3770         l3_file->cur_pos_in_phys_rec = 0;
3771         l3_file->cur_phys_rec++;
3772      }
3773      (* out_reclen) = reclen;
3774   }
3775   else
3776   {
3777      /* fixed len records */
3778      reclen = get_file_reclen(&l3_file->l2_file);
3779      if (is_eof(l3_file))
3780         return IMGTOOLERR_UNEXPECTED;
3781      if ((l3_file->cur_pos_in_phys_rec + reclen) > 256)
3782      {
3783         l3_file->cur_pos_in_phys_rec = 0;
3784         l3_file->cur_phys_rec++;
3785      }
3786      if ((l3_file->cur_phys_rec >= fphysrecs)
3787            || ((l3_file->cur_phys_rec == (fphysrecs-1))
3788               && ((l3_file->cur_pos_in_phys_rec + reclen) >= (fdr_eof ? fdr_eof : 256))))
3789         return IMGTOOLERR_CORRUPTIMAGE;
3790      errorcode = read_file_physrec(&l3_file->l2_file, l3_file->cur_phys_rec, physrec_buf);
3791      if (errorcode)
3792         return errorcode;
3793      memcpy(dest, physrec_buf + l3_file->cur_pos_in_phys_rec, reclen);
3794      l3_file->cur_pos_in_phys_rec += reclen;
3795      if (l3_file->cur_pos_in_phys_rec == 256)
3796      {
3797         l3_file->cur_pos_in_phys_rec = 0;
3798         l3_file->cur_phys_rec++;
3799      }
3800      (* out_reclen) = reclen;
3801   }
3802
3803   return 0;
3804}
3805#endif
3806
3807#if 0
3808#pragma mark -
3809#pragma mark IMGTOOL MODULE IMPLEMENTATION
3810#endif
3811
3812/*
3813   ti99 catalog iterator, used when imgtool reads the catalog
3814*/
3815typedef struct dsk_iterator
3816{
3817   ti99_lvl2_imgref *image;
3818   int level;
3819   int listing_subdirs;      /* true if we are listing subdirectories at current level */
3820   int index[2];            /* current index in the disk catalog */
3821   ti99_catalog *cur_catalog;   /* current catalog */
3822} dsk_iterator;
3823
3824typedef struct win_iterator
3825{
3826   ti99_lvl2_imgref *image;
3827   int level;
3828   int listing_subdirs;      /* true if we are listing subdirectories at current level */
3829   int index[MAX_DIR_LEVEL];   /* current index in the disk catalog */
3830   ti99_catalog catalog[MAX_DIR_LEVEL];   /* current catalog */
3831} win_iterator;
3832
3833
3834static imgtoolerr_t dsk_image_init_mess(imgtool_image *image, imgtool_stream *f);
3835static imgtoolerr_t dsk_image_init_v9t9(imgtool_image *image, imgtool_stream *f);
3836static imgtoolerr_t dsk_image_init_pc99_fm(imgtool_image *image, imgtool_stream *f);
3837static imgtoolerr_t dsk_image_init_pc99_mfm(imgtool_image *image, imgtool_stream *f);
3838static imgtoolerr_t win_image_init(imgtool_image *image, imgtool_stream *f);
3839static void ti99_image_exit(imgtool_image *img);
3840static void ti99_image_info(imgtool_image *img, char *string, size_t len);
3841static imgtoolerr_t dsk_image_beginenum(imgtool_directory *enumeration, const char *path);
3842static imgtoolerr_t dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
3843static imgtoolerr_t win_image_beginenum(imgtool_directory *enumeration, const char *path);
3844static imgtoolerr_t win_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
3845static imgtoolerr_t ti99_image_freespace(imgtool_partition *partition, UINT64 *size);
3846static imgtoolerr_t ti99_image_readfile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *destf);
3847static imgtoolerr_t ti99_image_writefile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions);
3848static imgtoolerr_t dsk_image_deletefile(imgtool_partition *partition, const char *fpath);
3849static imgtoolerr_t win_image_deletefile(imgtool_partition *partition, const char *fpath);
3850static imgtoolerr_t dsk_image_create_mess(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions);
3851static imgtoolerr_t dsk_image_create_v9t9(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions);
3852
3853enum
3854{
3855   dsk_createopts_volname = 'A',
3856   dsk_createopts_sides = 'B',
3857   dsk_createopts_tracks = 'C',
3858   dsk_createopts_sectors = 'D',
3859   dsk_createopts_protection = 'E',
3860   dsk_createopts_density = 'F'
3861};
3862
3863OPTION_GUIDE_START( dsk_create_optionguide )
3864   OPTION_STRING(dsk_createopts_volname, "label",   "Volume name" )
3865   OPTION_INT(dsk_createopts_sides, "sides", "Sides" )
3866   OPTION_INT(dsk_createopts_tracks, "tracks", "Tracks" )
3867   OPTION_INT(dsk_createopts_sectors, "sectors",   "Sectors (1->9 for SD, 1->18 for DD, 1->36 for HD)" )
3868   OPTION_INT(dsk_createopts_protection, "protection", "Protection (0 for normal, 1 for protected)" )
3869   OPTION_ENUM_START(dsk_createopts_density, "density", "Density" )
3870      OPTION_ENUM(   0,      "Auto",            "Auto" )
3871      OPTION_ENUM(   1,      "SD",            "Single Density" )
3872      OPTION_ENUM(   2,      "DD",            "Double Density" )
3873      OPTION_ENUM(   3,      "HD",            "High Density" )
3874   OPTION_ENUM_END
3875OPTION_GUIDE_END
3876
3877#define dsk_create_optionspecs "B1-[2];C1-[40]-80;D1-[18]-36;E[0]-1;F[0]-3"
3878
3879static void ti99_getinfo(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3880{
3881   switch(state)
3882   {
3883      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(ti99_lvl2_imgref); break;
3884      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(dsk_iterator); break;
3885
3886      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
3887      case IMGTOOLINFO_PTR_CLOSE:                     info->close = ti99_image_exit; break;
3888      case IMGTOOLINFO_PTR_INFO:                     info->info = ti99_image_info; break;
3889      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = ti99_image_freespace; break;
3890      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = ti99_image_readfile; break;
3891      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = ti99_image_writefile; break;
3892   }
3893}
3894
3895static void ti99_dsk_getinfo(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3896{
3897   switch(state)
3898   {
3899      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "dsk"); break;
3900      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = dsk_image_beginenum; break;
3901      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = dsk_image_nextenum; break;
3902      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = dsk_image_deletefile; break;
3903      default:                                 ti99_getinfo(imgclass, state, info);
3904   }
3905}
3906
3907void ti99_old_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3908{
3909   switch(state)
3910   {
3911      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "ti99_old"); break;
3912      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (old MESS format)"); break;
3913      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_mess; break;
3914      case IMGTOOLINFO_PTR_CREATE:            info->create = dsk_image_create_mess; break;
3915      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:   info->createimage_optguide = dsk_create_optionguide; break;
3916      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:   strcpy(info->s = imgtool_temp_str(), dsk_create_optionspecs); break;
3917      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3918   }
3919}
3920
3921void ti99_v9t9_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3922{
3923   switch(state)
3924   {
3925      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "v9t9"); break;
3926      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (V9T9 format)"); break;
3927      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_v9t9; break;
3928      case IMGTOOLINFO_PTR_CREATE:            info->create = dsk_image_create_v9t9; break;
3929      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:   info->createimage_optguide = dsk_create_optionguide; break;
3930      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:   strcpy(info->s = imgtool_temp_str(), dsk_create_optionspecs); break;
3931      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3932   }
3933}
3934
3935void ti99_pc99fm_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3936{
3937   switch(state)
3938   {
3939      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "pc99fm"); break;
3940      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (PC99 FM format)"); break;
3941      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_pc99_fm; break;
3942      case IMGTOOLINFO_PTR_CREATE:            /* info->create = dsk_image_create_pc99fm; */ break;
3943      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3944   }
3945}
3946
3947void ti99_pc99mfm_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3948{
3949   switch(state)
3950   {
3951      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "pc99mfm"); break;
3952      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (PC99 MFM format)"); break;
3953      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_pc99_mfm; break;
3954      case IMGTOOLINFO_PTR_CREATE:            /* info->create = dsk_image_create_pc99mfm; */ break;
3955      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3956   }
3957}
3958
3959void ti99_ti99hd_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3960{
3961   switch(state)
3962   {
3963      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "ti99hd"); break;
3964      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Harddisk"); break;
3965      case IMGTOOLINFO_PTR_OPEN:               info->open = win_image_init; break;
3966      case IMGTOOLINFO_PTR_CREATE:            /* info->create = hd_image_create; */ break;
3967
3968      case IMGTOOLINFO_STR_FILE_EXTENSIONS:      strcpy(info->s = imgtool_temp_str(), "hd"); break;
3969      case IMGTOOLINFO_PTR_BEGIN_ENUM:         info->begin_enum = win_image_beginenum; break;
3970      case IMGTOOLINFO_PTR_NEXT_ENUM:            info->next_enum = win_image_nextenum; break;
3971      case IMGTOOLINFO_PTR_DELETE_FILE:         info->delete_file = win_image_deletefile; break;
3972      default:                           ti99_getinfo(imgclass, state, info);
3973   }
3974}
3975
3976
3977
3978/*
3979   Open a file as a ti99_image (common code).
3980*/
3981static int dsk_image_init(imgtool_image *img, imgtool_stream *f, ti99_img_format img_format)
3982{
3983   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
3984   dsk_vib vib;
3985   int reply;
3986   int totphysrecs;
3987   unsigned fdir_aphysrec;
3988   int i;
3989
3990   /* open disk image at level 1 */
3991   reply = open_image_lvl1(f, img_format, &image->l1_img, &vib);
3992   if (reply)
3993      return reply;
3994
3995   /* open disk image at level 2 */
3996   image->type = L2I_DSK;
3997
3998   /* first compute AU size and number of AUs */
3999   totphysrecs = get_UINT16BE(vib.totphysrecs);
4000
4001   image->AUformat.physrecsperAU = (totphysrecs + 1599) / 1600;
4002   /* round to next larger power of 2 */
4003   for (i = 1; i < image->AUformat.physrecsperAU; i <<= 1)
4004      ;
4005   image->AUformat.physrecsperAU = i;
4006   image->AUformat.totAUs = totphysrecs / image->AUformat.physrecsperAU;
4007
4008   /* extract number of physrecs */
4009   image->u.dsk.totphysrecs = get_UINT16BE(vib.totphysrecs);
4010
4011   /* read and check main volume catalog */
4012   reply = dsk_read_catalog(image, 1, &image->u.dsk.catalogs[0]);
4013   if (reply)
4014      return reply;
4015
4016   image->u.dsk.fdir_aphysrec[0] = 1;
4017
4018   /* read and check subdirectory catalogs */
4019   /* Note that the reserved areas used for HFDC subdirs may be used for other
4020   purposes by other FDRs, so, if we get any error, we will assume there is no
4021   subdir after all... */
4022   image->u.dsk.catalogs[0].num_subdirs = 0;
4023   for (i=0; i<3; i++)
4024   {
4025      fdir_aphysrec = get_UINT16BE(vib.subdir[i].fdir_aphysrec);
4026      if ((! memcmp(vib.subdir[i].name, "\0\0\0\0\0\0\0\0\0\0", 10))
4027            || (! memcmp(vib.subdir[i].name, "          ", 10)))
4028      {
4029         /* name is empty: fine with us unless there is a fdir pointer */
4030         if (fdir_aphysrec != 0)
4031         {
4032            image->u.dsk.catalogs[0].num_subdirs = 0;
4033            break;
4034         }
4035      }
4036      else if (check_fname(vib.subdir[i].name))
4037      {
4038         /* name is invalid: this is not an HFDC format floppy */
4039         image->u.dsk.catalogs[0].num_subdirs = 0;
4040         break;
4041      }
4042      else
4043      {
4044         /* there is a non-empty name */
4045         if ((fdir_aphysrec == 0) || (fdir_aphysrec >= totphysrecs))
4046         {
4047            /* error: fdir pointer is invalid or NULL */
4048            image->u.dsk.catalogs[0].num_subdirs = 0;
4049            break;
4050         }
4051         /* fill in descriptor fields */
4052         image->u.dsk.fdir_aphysrec[image->u.dsk.catalogs[0].num_subdirs+1] = fdir_aphysrec;
4053         /*image->u.dsk.catalogs[0].subdirs[image->u.dsk.catalogs[0].num_subdirs].dir_ptr = fdir_aphysrec;*/
4054         memcpy(image->u.dsk.catalogs[0].subdirs[image->u.dsk.catalogs[0].num_subdirs].name, vib.subdir[i].name, 10);
4055         reply = dsk_read_catalog(image, fdir_aphysrec, &image->u.dsk.catalogs[image->u.dsk.catalogs[0].num_subdirs+1]);
4056         if (reply)
4057         {
4058            /* error: invalid fdir */
4059            image->u.dsk.catalogs[0].num_subdirs = 0;
4060            break;
4061         }
4062         /* found valid subdirectory: increment subdir count */
4063         image->u.dsk.catalogs[0].num_subdirs++;
4064      }
4065   }
4066
4067   /* extract volume name */
4068   memcpy(image->vol_name, vib.name, 10);
4069
4070   /* initialize default data_offset */
4071   image->data_offset = 32+2;
4072
4073   return 0;
4074}
4075
4076/*
4077   Open a file as a ti99_image (MESS format).
4078*/
4079static imgtoolerr_t dsk_image_init_mess(imgtool_image *image, imgtool_stream *f)
4080{
4081   return dsk_image_init(image, f, if_mess);
4082}
4083
4084/*
4085   Open a file as a ti99_image (V9T9 format).
4086*/
4087static imgtoolerr_t dsk_image_init_v9t9(imgtool_image *image, imgtool_stream *f)
4088{
4089   return dsk_image_init(image, f, if_v9t9);
4090}
4091
4092/*
4093   Open a file as a ti99_image (PC99 FM format).
4094*/
4095static imgtoolerr_t dsk_image_init_pc99_fm(imgtool_image *image, imgtool_stream *f)
4096{
4097   return dsk_image_init(image, f, if_pc99_fm);
4098}
4099
4100/*
4101   Open a file as a ti99_image (PC99 MFM format).
4102*/
4103static imgtoolerr_t dsk_image_init_pc99_mfm(imgtool_image *image, imgtool_stream *f)
4104{
4105   return dsk_image_init(image, f, if_pc99_mfm);
4106}
4107
4108/*
4109   Open a file as a ti99_image (harddisk format).
4110*/
4111static imgtoolerr_t win_image_init(imgtool_image *img, imgtool_stream *f)
4112{
4113   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4114   win_vib_ddr vib;
4115   int reply;
4116   int i;
4117
4118   /* open disk image at level 1 */
4119   reply = open_image_lvl1(f, if_harddisk, & image->l1_img, NULL);
4120   if (reply)
4121      return reply;
4122
4123   /* open disk image at level 2 */
4124   image->type = L2I_WIN;
4125
4126   /* read VIB */
4127   reply = read_absolute_physrec(&image->l1_img, 0, &vib);
4128   if (reply)
4129      return reply;
4130
4131   /* guess VIB version */
4132   image->u.win.vib_version = memcmp(vib.u.vib_v1.id, "WIN", 3) ? win_vib_v2 : win_vib_v1;
4133
4134   /* extract AU size and number of AUs */
4135   image->AUformat.physrecsperAU = ((get_UINT16BE(vib.params) >> 12) & 0xf) + 1;
4136   image->AUformat.totAUs = get_UINT16BE(vib.totAUs);
4137
4138   /* extract volume name */
4139   memcpy(image->vol_name, vib.name, 10);
4140
4141   /* extract data_offset */
4142   switch (image->u.win.vib_version)
4143   {
4144   case win_vib_v1:
4145      image->data_offset = 64;
4146      break;
4147
4148   case win_vib_v2:
4149      image->data_offset = vib.u.vib_v2.res_AUs * 64;
4150      break;
4151   }
4152
4153   /* read allocation bitmap (aphysrecs 1 through n, n<=33) */
4154   for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
4155   {
4156      reply = read_absolute_physrec(&image->l1_img, i+1, image->abm+i*256);
4157      if (reply)
4158         return reply;
4159   }
4160
4161   return 0;
4162}
4163
4164/*
4165   close a ti99_image
4166*/
4167static void ti99_image_exit(imgtool_image *img)
4168{
4169   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4170
4171   close_image_lvl1(&image->l1_img);
4172}
4173
4174/*
4175   get basic information on a ti99_image
4176
4177   Currently returns the volume name
4178*/
4179static void ti99_image_info(imgtool_image *img, char *string, size_t len)
4180{
4181   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4182   char vol_name[11];
4183
4184   fname_to_str(vol_name, image->vol_name, 11);
4185
4186   snprintf(string, len, "%s", vol_name);
4187}
4188
4189/*
4190   Open the disk catalog for enumeration
4191*/
4192static imgtoolerr_t dsk_image_beginenum(imgtool_directory *enumeration, const char *path)
4193{
4194   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
4195   dsk_iterator *iter = (dsk_iterator *) imgtool_directory_extrabytes(enumeration);
4196
4197   iter->image = image;
4198   iter->level = 0;
4199   iter->listing_subdirs = 1;
4200   iter->index[0] = 0;
4201   iter->cur_catalog = &iter->image->u.dsk.catalogs[0];
4202
4203   return 0;
4204}
4205
4206/*
4207   Enumerate disk catalog next entry
4208*/
4209static imgtoolerr_t dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
4210{
4211   dsk_iterator *iter = (dsk_iterator*) imgtool_directory_extrabytes(enumeration);
4212   dsk_fdr fdr;
4213   int reply;
4214   unsigned fdr_aphysrec;
4215
4216
4217   ent->corrupt = 0;
4218   ent->eof = 0;
4219
4220   /* iterate through catalogs to next file or dir entry */
4221   while ((iter->level >= 0)
4222         && (iter->index[iter->level] >= (iter->listing_subdirs
4223                                    ? iter->cur_catalog->num_subdirs
4224                                    : iter->cur_catalog->num_files)))
4225   {
4226      if (iter->listing_subdirs)
4227      {
4228         iter->listing_subdirs = 0;
4229         iter->index[iter->level] = 0;
4230      }
4231      else
4232      {
4233         iter->listing_subdirs = 1;
4234         if (! iter->level)
4235            iter->level = -1;
4236         else
4237         {
4238            iter->level = 0;
4239            iter->index[0]++;
4240            iter->cur_catalog = &iter->image->u.dsk.catalogs[0];
4241         }
4242      }
4243   }
4244
4245   if (iter->level < 0)
4246   {
4247      ent->eof = 1;
4248   }
4249   else
4250   {
4251      if (iter->listing_subdirs)
4252      {
4253         fname_to_str(ent->filename, iter->image->u.dsk.catalogs[0].subdirs[iter->index[iter->level]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4254
4255         /* set type of DIR */
4256         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "DIR");
4257
4258         /* len in physrecs */
4259         ent->filesize = 1;
4260
4261         /* recurse subdirectory */
4262         iter->listing_subdirs = 0;   /* no need to list subdirs as only the
4263                              root dir has subdirs in DSK format */
4264         iter->level = 1;
4265         iter->cur_catalog = &iter->image->u.dsk.catalogs[iter->index[0]+1];
4266         iter->index[iter->level] = 0;
4267      }
4268      else
4269      {
4270         fdr_aphysrec = iter->cur_catalog->files[iter->index[iter->level]].fdr_ptr;
4271         reply = read_absolute_physrec(& iter->image->l1_img, fdr_aphysrec, & fdr);
4272         if (reply)
4273            return IMGTOOLERR_READERROR;
4274#if 0
4275         fname_to_str(ent->filename, fdr.name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4276#else
4277         {
4278            char buf[11];
4279
4280            ent->filename[0] = '\0';
4281            if (iter->level)
4282            {
4283               fname_to_str(ent->filename, iter->image->u.dsk.catalogs[0].subdirs[iter->index[0]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4284               strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4285            }
4286            fname_to_str(buf, fdr.name, 11);
4287            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4288         }
4289#endif
4290         /* parse flags */
4291         if (fdr.flags & fdr99_f_program)
4292            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "PGM%s",
4293                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4294         else
4295            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%c/%c %d%s",
4296                     (fdr.flags & fdr99_f_int) ? 'I' : 'D',
4297                     (fdr.flags & fdr99_f_var) ? 'V' : 'F',
4298                     fdr.reclen,
4299                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4300         /* len in physrecs */
4301         ent->filesize = get_UINT16BE(fdr.fphysrecs);
4302
4303         iter->index[iter->level]++;
4304      }
4305   }
4306
4307   return 0;
4308}
4309
4310/*
4311   Open the disk catalog for enumeration
4312*/
4313static imgtoolerr_t win_image_beginenum(imgtool_directory *enumeration, const char *path)
4314{
4315   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
4316   win_iterator *iter = (win_iterator *) imgtool_directory_extrabytes(enumeration);
4317   imgtoolerr_t errorcode;
4318
4319   iter->image = image;
4320   iter->level = 0;
4321   iter->listing_subdirs = 1;
4322   iter->index[0] = 0;
4323   errorcode = win_read_catalog(image, 0, &iter->catalog[0]);
4324   if (errorcode)
4325      return errorcode;
4326
4327   return 0;
4328}
4329
4330/*
4331   Enumerate disk catalog next entry
4332*/
4333static imgtoolerr_t win_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
4334{
4335   win_iterator *iter = (win_iterator *) imgtool_directory_extrabytes(enumeration);
4336   unsigned fdr_aphysrec;
4337   win_fdr fdr;
4338   int reply;
4339   int i;
4340
4341
4342   ent->corrupt = 0;
4343   ent->eof = 0;
4344
4345   /* iterate through catalogs to next file or dir entry */
4346   while ((iter->level >= 0)
4347         && (iter->index[iter->level] >= (iter->listing_subdirs
4348                                    ? iter->catalog[iter->level].num_subdirs
4349                                    : iter->catalog[iter->level].num_files)))
4350   {
4351      if (iter->listing_subdirs)
4352      {
4353         iter->listing_subdirs = 0;
4354         iter->index[iter->level] = 0;
4355      }
4356      else
4357      {
4358         iter->listing_subdirs = 1;
4359         iter->level--;
4360         iter->index[iter->level]++;
4361      }
4362   }
4363
4364   if (iter->level < 0)
4365   {
4366      ent->eof = 1;
4367   }
4368   else
4369   {
4370      if (iter->listing_subdirs)
4371      {
4372#if 0
4373         fname_to_str(ent->filename, iter->catalog[iter->level].subdirs[iter->index[iter->level]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4374#else
4375         {
4376            char buf[11];
4377
4378            ent->filename[0] = '\0';
4379            for (i=0; i<iter->level; i++)
4380            {
4381               fname_to_str(buf, iter->catalog[i].subdirs[iter->index[i]].name, 11);
4382               strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4383               strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4384            }
4385            fname_to_str(buf, iter->catalog[iter->level].subdirs[iter->index[iter->level]].name, 11);
4386            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4387         }
4388#endif
4389
4390         /* set type of DIR */
4391         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "DIR");
4392
4393         /* len in physrecs */
4394         ent->filesize = 2;
4395
4396         /* recurse subdirectory */
4397         /*iter->listing_subdirs = 1;*/
4398         iter->level++;
4399         iter->index[iter->level] = 0;
4400         reply = win_read_catalog(iter->image, iter->catalog[iter->level-1].subdirs[iter->index[iter->level-1]].dir_ptr, &iter->catalog[iter->level]);
4401         if (reply)
4402         {
4403            ent->corrupt = 1;
4404            return reply;
4405         }
4406      }
4407      else
4408      {
4409         fdr_aphysrec = iter->catalog[iter->level].files[iter->index[iter->level]].fdr_ptr*iter->image->AUformat.physrecsperAU;
4410         reply = read_absolute_physrec(& iter->image->l1_img, fdr_aphysrec, & fdr);
4411         if (reply)
4412            return IMGTOOLERR_READERROR;
4413#if 0
4414         fname_to_str(ent->filename, iter->catalog[iter->level].files[iter->index[iter->level]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4415#else
4416         {
4417            char buf[11];
4418
4419            ent->filename[0] = '\0';
4420            for (i=0; i<iter->level; i++)
4421            {
4422               fname_to_str(buf, iter->catalog[i].subdirs[iter->index[i]].name, 11);
4423               strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4424               strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4425            }
4426            fname_to_str(buf, iter->catalog[iter->level].files[iter->index[iter->level]].name, 11);
4427            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4428         }
4429#endif
4430         /* parse flags */
4431         if (fdr.flags & fdr99_f_program)
4432            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "PGM%s",
4433                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4434         else
4435            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%c/%c %d%s",
4436                     (fdr.flags & fdr99_f_int) ? 'I' : 'D',
4437                     (fdr.flags & fdr99_f_var) ? 'V' : 'F',
4438                     fdr.reclen,
4439                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4440         /* len in physrecs */
4441         ent->filesize = get_win_fdr_fphysrecs(&fdr);
4442
4443         iter->index[iter->level]++;
4444      }
4445   }
4446
4447   return 0;
4448}
4449
4450/*
4451   Compute free space on disk image (in AUs)
4452*/
4453static imgtoolerr_t ti99_image_freespace(imgtool_partition *partition, UINT64 *size)
4454{
4455   imgtool_image *img = imgtool_partition_image(partition);
4456   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4457   size_t freeAUs;
4458   int i;
4459
4460   freeAUs = 0;
4461   for (i=0; i<image->AUformat.totAUs; i++)
4462   {
4463      if (! (image->abm[i >> 3] & (1 << (i & 7))))
4464         freeAUs++;
4465   }
4466
4467   *size = freeAUs;
4468
4469   return IMGTOOLERR_SUCCESS;
4470}
4471
4472/*
4473   Extract a file from a ti99_image.  The file is saved in tifile format.
4474*/
4475static imgtoolerr_t ti99_image_readfile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *destf)
4476{
4477   imgtool_image *img = imgtool_partition_image(partition);
4478#if 1
4479
4480   /* extract data as TIFILES */
4481   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4482   ti99_lvl2_fileref src_file;
4483   ti99_lvl2_fileref dst_file;
4484   ti99_date_time date_time;
4485   int fphysrecs;
4486   int i;
4487   UINT8 buf[256];
4488   imgtoolerr_t errorcode;
4489
4490
4491   if (check_fpath(fpath))
4492      return IMGTOOLERR_BADFILENAME;
4493
4494   /* open file on TI image */
4495   switch (image->type)
4496   {
4497   case L2I_DSK:
4498      errorcode = open_file_lvl2_dsk(image, fpath, &src_file);
4499      break;
4500
4501   case L2I_WIN:
4502      errorcode = open_file_lvl2_win(image, fpath, &src_file);
4503      break;
4504
4505   default:
4506      errorcode = -1;
4507      break;
4508   }
4509   if (errorcode)
4510      return errorcode;
4511
4512   errorcode = new_file_lvl2_tifiles(destf, &dst_file);
4513   if (errorcode)
4514      return errorcode;
4515
4516   /* write TIFILE header */
4517   /* set up parameters */
4518   set_file_flags(&dst_file, get_file_flags(&src_file));
4519   set_file_recsperphysrec(&dst_file, get_file_recsperphysrec(&src_file));
4520   errorcode = set_file_fphysrecs(&dst_file, get_file_fphysrecs(&src_file));
4521   if (errorcode)
4522      return errorcode;
4523   set_file_eof(&dst_file, get_file_eof(&src_file));
4524   errorcode = set_file_reclen(&dst_file, get_file_reclen(&src_file));
4525   if (errorcode)
4526      return errorcode;
4527   errorcode = set_file_fixrecs(&dst_file, get_file_fixrecs(&src_file));
4528   if (errorcode)
4529      return errorcode;
4530
4531   get_file_creation_date(&src_file, &date_time);
4532   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4533         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4534      current_date_time(&date_time);*/
4535   set_file_creation_date(&dst_file, date_time);
4536
4537   get_file_update_date(&src_file, &date_time);
4538   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4539         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4540      current_date_time(&date_time);*/
4541   set_file_update_date(&dst_file, date_time);
4542
4543   if (stream_write(destf, & dst_file.u.tifiles.hdr, 128) != 128)
4544      return IMGTOOLERR_WRITEERROR;
4545
4546   /* copy data to TIFILE */
4547   fphysrecs = get_file_fphysrecs(&src_file);
4548
4549   for (i=0; i<fphysrecs; i++)
4550   {
4551      errorcode = read_file_physrec(& src_file, i, buf);
4552      if (errorcode)
4553         return errorcode;
4554
4555      errorcode = write_file_physrec(& dst_file, i, buf);
4556      if (errorcode)
4557         return errorcode;
4558   }
4559
4560   return 0;
4561
4562#else
4563
4564   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4565   ti99_lvl3_fileref src_file;
4566   UINT8 buf[256];
4567   int reclen;
4568   char lineend = '\r';
4569   int errorcode;
4570
4571
4572   if (check_fpath(fpath))
4573      return IMGTOOLERR_BADFILENAME;
4574
4575   /* open file on TI image */
4576   switch (image->type)
4577   {
4578   case L2I_DSK:
4579      errorcode = open_file_lvl2_dsk(image, fpath, &src_file.l2_file);
4580      break;
4581
4582   case L2I_WIN:
4583      errorcode = open_file_lvl2_win(image, fpath, &src_file.l2_file);
4584      break;
4585   }
4586   if (errorcode)
4587      return errorcode;
4588
4589   errorcode = open_file_lvl3(& src_file);
4590   if (errorcode)
4591      return errorcode;
4592
4593   /* write text data */
4594   while (! is_eof(& src_file))
4595   {
4596      errorcode = read_next_record(& src_file, buf, & reclen);
4597      if (errorcode)
4598         return errorcode;
4599      if (stream_write(destf, buf, reclen) != reclen)
4600         return IMGTOOLERR_WRITEERROR;
4601      if (stream_write(destf, &lineend, 1) != 1)
4602         return IMGTOOLERR_WRITEERROR;
4603   }
4604
4605   return 0;
4606
4607#endif
4608}
4609
4610/*
4611   Add a file to a ti99_image.  The file must be in tifile format.
4612*/
4613static imgtoolerr_t ti99_image_writefile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
4614{
4615   imgtool_image *img = imgtool_partition_image(partition);
4616   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4617   const char *filename;
4618   char ti_fname[10];
4619   ti99_lvl2_fileref src_file;
4620   ti99_lvl2_fileref dst_file;
4621   ti99_date_time date_time;
4622   int i;
4623   int fphysrecs;
4624   UINT8 buf[256];
4625   imgtoolerr_t errorcode;
4626   int parent_ref_valid, parent_ref = 0;
4627   ti99_catalog *catalog, catalog_buf = {0, };
4628
4629
4630   (void) writeoptions;
4631
4632   if (check_fpath(fpath))
4633      return IMGTOOLERR_BADFILENAME;
4634
4635   switch (image->type)
4636   {
4637   case L2I_DSK:
4638      errorcode = dsk_find_catalog_entry(image, fpath, &parent_ref_valid, &parent_ref, NULL, NULL);
4639      if (errorcode == 0)
4640         /* file already exists: causes an error for now */
4641         return IMGTOOLERR_UNEXPECTED;
4642      else if ((! parent_ref_valid) || (errorcode != IMGTOOLERR_FILENOTFOUND))
4643         return errorcode;
4644      break;
4645
4646   case L2I_WIN:
4647      errorcode = win_find_catalog_entry(image, fpath, &parent_ref_valid, &parent_ref, &catalog_buf, NULL, NULL);
4648      if (errorcode == 0)
4649         /* file already exists: causes an error for now */
4650         return IMGTOOLERR_UNEXPECTED;
4651      else if ((! parent_ref_valid) || (errorcode != IMGTOOLERR_FILENOTFOUND))
4652         return errorcode;
4653      break;
4654   }
4655
4656   errorcode = open_file_lvl2_tifiles(sourcef, & src_file);
4657   if (errorcode)
4658      return errorcode;
4659
4660   /* create new file */
4661   filename = strrchr(fpath, '.');
4662   if (filename)
4663      filename++;
4664   else
4665      filename = fpath;
4666   str_to_fname(ti_fname, filename);
4667   switch (image->type)
4668   {
4669   case L2I_DSK:
4670      errorcode = new_file_lvl2_dsk(image, parent_ref, ti_fname, &dst_file);
4671      if (errorcode)
4672         return errorcode;
4673      break;
4674
4675   case L2I_WIN:
4676      errorcode = new_file_lvl2_win(image, &catalog_buf, ti_fname, &dst_file);
4677      if (errorcode)
4678         return errorcode;
4679      break;
4680   }
4681
4682   /* set up parameters */
4683   set_file_flags(&dst_file, get_file_flags(&src_file));
4684   set_file_recsperphysrec(&dst_file, get_file_recsperphysrec(&src_file));
4685   errorcode = set_file_fphysrecs(&dst_file, /*get_file_fphysrecs(&src_file)*/0);
4686   if (errorcode)
4687      return errorcode;
4688   set_file_eof(&dst_file, get_file_eof(&src_file));
4689   errorcode = set_file_reclen(&dst_file, get_file_reclen(&src_file));
4690   if (errorcode)
4691      return errorcode;
4692   errorcode = set_file_fixrecs(&dst_file, get_file_fixrecs(&src_file));
4693   if (errorcode)
4694      return errorcode;
4695
4696   get_file_creation_date(&src_file, &date_time);
4697   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4698         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4699      current_date_time(&date_time);*/
4700   set_file_creation_date(&dst_file, date_time);
4701
4702   get_file_update_date(&src_file, &date_time);
4703   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4704         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4705      current_date_time(&date_time);*/
4706   set_file_update_date(&dst_file, date_time);
4707
4708   /* alloc data physrecs */
4709   fphysrecs = get_file_fphysrecs(&src_file);
4710   switch (dst_file.type)
4711   {
4712   case L2F_DSK:
4713      errorcode = dsk_alloc_file_physrecs(&dst_file.u.dsk, fphysrecs);
4714      if (errorcode)
4715         return errorcode;
4716      break;
4717
4718   case L2F_WIN:
4719      errorcode = win_alloc_file_physrecs(&dst_file.u.win, fphysrecs);
4720      if (errorcode)
4721         return errorcode;
4722      break;
4723
4724   case L2F_TIFILES:
4725      break;
4726   }
4727
4728   /* copy data */
4729   for (i=0; i<fphysrecs; i++)
4730   {
4731      if (stream_read(sourcef, buf, 256) != 256)
4732         return IMGTOOLERR_READERROR;
4733
4734      errorcode = write_file_physrec(& dst_file, i, buf);
4735      if (errorcode)
4736         return errorcode;
4737   }
4738
4739   /* write fdr */
4740   switch (image->type)
4741   {
4742   case L2I_DSK:
4743      if (write_absolute_physrec(& image->l1_img, dst_file.u.dsk.fdr_aphysrec, &dst_file.u.dsk.fdr))
4744         return IMGTOOLERR_WRITEERROR;
4745      break;
4746
4747   case L2I_WIN:
4748      /* save fphysrecs field as well */
4749      if (dst_file.u.win.curfdr_aphysrec == dst_file.u.win.eldestfdr_aphysrec)
4750         set_win_fdr_fphysrecs(&dst_file.u.win.curfdr, dst_file.u.win.fphysrecs);
4751      if (write_absolute_physrec(& image->l1_img, dst_file.u.win.curfdr_aphysrec, &dst_file.u.win.curfdr))
4752         return IMGTOOLERR_WRITEERROR;
4753      if (dst_file.u.win.curfdr_aphysrec != dst_file.u.win.eldestfdr_aphysrec)
4754      {
4755         dst_file.u.win.curfdr_aphysrec = dst_file.u.win.eldestfdr_aphysrec;
4756         if (read_absolute_physrec(& image->l1_img, dst_file.u.win.curfdr_aphysrec, &dst_file.u.win.curfdr))
4757            return IMGTOOLERR_WRITEERROR;
4758         set_win_fdr_fphysrecs(&dst_file.u.win.curfdr, dst_file.u.win.fphysrecs);
4759         if (write_absolute_physrec(& image->l1_img, dst_file.u.win.curfdr_aphysrec, &dst_file.u.win.curfdr))
4760            return IMGTOOLERR_WRITEERROR;
4761      }
4762      break;
4763   }
4764
4765   /* update catalog */
4766   switch (image->type)
4767   {
4768   case L2I_DSK:
4769      catalog = &image->u.dsk.catalogs[parent_ref];
4770      for (i=0; i<128; i++)
4771      {
4772         buf[2*i] = catalog->files[i].fdr_ptr >> 8;
4773         buf[2*i+1] = catalog->files[i].fdr_ptr & 0xff;
4774      }
4775      if (write_absolute_physrec(& image->l1_img, image->u.dsk.fdir_aphysrec[parent_ref], buf))
4776         return IMGTOOLERR_WRITEERROR;
4777      break;
4778
4779   case L2I_WIN:
4780      {
4781         win_vib_ddr parent_ddr;
4782         int fdir_AU;
4783
4784         /* update VIB/DDR and get FDIR AU address */
4785         if (read_absolute_physrec(& image->l1_img, parent_ref * image->AUformat.physrecsperAU, &parent_ddr))
4786            return IMGTOOLERR_READERROR;
4787         parent_ddr.num_files = catalog_buf.num_files;
4788         if (write_absolute_physrec(& image->l1_img, parent_ref * image->AUformat.physrecsperAU, &parent_ddr))
4789            return IMGTOOLERR_WRITEERROR;
4790         fdir_AU = get_UINT16BE(parent_ddr.fdir_AU);
4791
4792         /* generate FDIR and save it */
4793         for (i=0; i<127; i++)
4794         {
4795            buf[2*i] = catalog_buf.files[i].fdr_ptr >> 8;
4796            buf[2*i+1] = catalog_buf.files[i].fdr_ptr & 0xff;
4797         }
4798         buf[254] = parent_ref >> 8;
4799         buf[255] = parent_ref & 0xff;
4800         if (write_absolute_physrec(& image->l1_img, fdir_AU * image->AUformat.physrecsperAU, buf))
4801            return IMGTOOLERR_WRITEERROR;
4802      }
4803      break;
4804   }
4805
4806   /* update bitmap */
4807   switch (image->type)
4808   {
4809   case L2I_DSK:
4810      {
4811         dsk_vib vib;
4812
4813         if (read_absolute_physrec(& image->l1_img, 0, &vib))
4814            return IMGTOOLERR_READERROR;
4815         memcpy(vib.abm, image->abm, 200);
4816         if (write_absolute_physrec(& image->l1_img, 0, &vib))
4817            return IMGTOOLERR_WRITEERROR;
4818      }
4819      break;
4820
4821   case L2I_WIN:
4822      /* save allocation bitmap (aphysrecs 1 through n, n<=33) */
4823      for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
4824         if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
4825            return IMGTOOLERR_WRITEERROR;
4826      break;
4827   }
4828
4829   return 0;
4830}
4831
4832/*
4833   Delete a file from a ti99_image.
4834*/
4835static imgtoolerr_t dsk_image_deletefile(imgtool_partition *partition, const char *fpath)
4836{
4837   imgtool_image *img = imgtool_partition_image(partition);
4838   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4839   dsk_fdr fdr;
4840   int i, cluster_index;
4841   unsigned cur_AU, cluster_lastfphysrec;
4842   int fphysrecs;
4843   int parent_ref, is_dir, catalog_index;
4844   imgtoolerr_t errorcode;
4845   UINT8 buf[256];
4846   ti99_catalog *catalog;
4847
4848
4849   if (check_fpath(fpath))
4850      return IMGTOOLERR_BADFILENAME;
4851
4852   errorcode = dsk_find_catalog_entry(image, fpath, NULL, &parent_ref, &is_dir, &catalog_index);
4853   if (errorcode)
4854      return errorcode;
4855
4856   if (is_dir)
4857   {
4858      catalog = &image->u.dsk.catalogs[catalog_index+1];
4859
4860      if ((catalog->num_files != 0) || (catalog->num_subdirs != 0))
4861         return IMGTOOLERR_UNIMPLEMENTED;
4862
4863      catalog = &image->u.dsk.catalogs[0];
4864
4865      /* free fdir AU */
4866      cur_AU = image->u.dsk.fdir_aphysrec[catalog_index+1] / image->AUformat.physrecsperAU;
4867      image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
4868
4869      /* delete catalog entry */
4870      for (i=catalog_index; i<2; i++)
4871      {
4872         catalog->subdirs[i] = catalog->subdirs[i+1];
4873         image->u.dsk.fdir_aphysrec[i+1] = image->u.dsk.fdir_aphysrec[i+2];
4874      }
4875      memset(catalog->subdirs[2].name, 0, 10);
4876      catalog->subdirs[2].dir_ptr = 0;
4877      image->u.dsk.fdir_aphysrec[3] = 0;
4878      catalog->num_subdirs--;
4879
4880      /* update directory and bitmap in vib */
4881      {
4882         dsk_vib vib;
4883
4884         if (read_absolute_physrec(& image->l1_img, 0, &vib))
4885            return IMGTOOLERR_READERROR;
4886
4887         for (i=0; i<3; i++)
4888         {
4889            memcpy(vib.subdir[i].name, catalog->subdirs[i].name, 10);
4890            set_UINT16BE(&vib.subdir[i].fdir_aphysrec, image->u.dsk.fdir_aphysrec[i+1]);
4891         }
4892
4893         memcpy(vib.abm, image->abm, 200);
4894
4895         if (write_absolute_physrec(& image->l1_img, 0, &vib))
4896            return IMGTOOLERR_WRITEERROR;
4897      }
4898   }
4899   else
4900   {
4901      catalog = &image->u.dsk.catalogs[parent_ref];
4902
4903      if (read_absolute_physrec(& image->l1_img, catalog->files[catalog_index].fdr_ptr, &fdr))
4904         return IMGTOOLERR_READERROR;
4905
4906      /* free data AUs */
4907      fphysrecs = get_UINT16BE(fdr.fphysrecs);
4908
4909      i = 0;
4910      cluster_index = 0;
4911      while (cluster_index < 76)
4912      {
4913         cur_AU = get_dsk_fdr_cluster_baseAU(image, & fdr, cluster_index);
4914         if (cur_AU == 0)
4915            /* end of cluster list */
4916            break;
4917         cluster_lastfphysrec = get_dsk_fdr_cluster_lastfphysrec(& fdr, cluster_index);
4918
4919         while (i<=cluster_lastfphysrec)
4920         {
4921            /* the condition below is an error, but it should not prevent
4922            us from deleting the file */
4923            if (cur_AU >= image->AUformat.totAUs)
4924               /*return IMGTOOLERR_CORRUPTIMAGE;*/
4925               break;
4926
4927            image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
4928
4929            i += image->AUformat.physrecsperAU;
4930            cur_AU++;
4931         }
4932
4933         cluster_index++;
4934      }
4935      /* the condition below is an error, but it should not prevent us from
4936      deleting the file */
4937      /*if (i<fphysrecs)
4938         return IMGTOOLERR_CORRUPTIMAGE;*/
4939
4940      /* free fdr AU */
4941      cur_AU = catalog->files[catalog_index].fdr_ptr / image->AUformat.physrecsperAU;
4942      image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
4943
4944      /* delete catalog entry */
4945      for (i=catalog_index; i<127; i++)
4946         catalog->files[i] = catalog->files[i+1];
4947      catalog->files[127].fdr_ptr = 0;
4948      catalog->num_files--;
4949
4950      /* update parent fdir */
4951      for (i=0; i<128; i++)
4952      {
4953         buf[2*i] = catalog->files[i].fdr_ptr >> 8;
4954         buf[2*i+1] = catalog->files[i].fdr_ptr & 0xff;
4955      }
4956      if (write_absolute_physrec(& image->l1_img, image->u.dsk.fdir_aphysrec[parent_ref], buf))
4957         return IMGTOOLERR_WRITEERROR;
4958
4959      /* update bitmap */
4960      {
4961         dsk_vib vib;
4962
4963         if (read_absolute_physrec(& image->l1_img, 0, &vib))
4964            return IMGTOOLERR_READERROR;
4965         memcpy(vib.abm, image->abm, 200);
4966         if (write_absolute_physrec(& image->l1_img, 0, &vib))
4967            return IMGTOOLERR_WRITEERROR;
4968      }
4969   }
4970
4971   return 0;
4972}
4973
4974static imgtoolerr_t win_image_deletefile(imgtool_partition *partition, const char *fpath)
4975{
4976   imgtool_image *img = imgtool_partition_image(partition);
4977   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4978   int parent_ddr_AU, is_dir, catalog_index;
4979   win_fdr fdr;
4980   int i;
4981   unsigned cur_AU, end_AU;
4982   unsigned curfdr_aphysrec;
4983   unsigned cursibFDR_index, endsibFDR_index = 0;
4984   int errorcode;
4985   UINT8 buf[256];
4986   ti99_catalog catalog;
4987
4988
4989   if (check_fpath(fpath))
4990      return IMGTOOLERR_BADFILENAME;
4991
4992   errorcode = win_find_catalog_entry(image, fpath, NULL, &parent_ddr_AU, &catalog, &is_dir, &catalog_index);
4993   if (errorcode)
4994      return errorcode;
4995
4996   if (is_dir)
4997   {
4998      unsigned DDR_AU;
4999      win_vib_ddr ddr_buf;
5000
5001      /* Read DDR record */
5002      DDR_AU = catalog.subdirs[catalog_index].dir_ptr;
5003      if (read_absolute_physrec(& image->l1_img, DDR_AU*image->AUformat.physrecsperAU, &ddr_buf))
5004         return IMGTOOLERR_READERROR;
5005
5006      /* read FDIR AU pointer */
5007      cur_AU = get_UINT16BE(ddr_buf.fdir_AU);
5008
5009      /* sanity checks */
5010      if ((ddr_buf.num_files > 127) || (ddr_buf.num_subdirs > 114) || (cur_AU > image->AUformat.totAUs))
5011         return IMGTOOLERR_CORRUPTIMAGE;
5012
5013      if ((ddr_buf.num_files != 0) || (ddr_buf.num_subdirs != 0))
5014         return IMGTOOLERR_UNIMPLEMENTED;
5015
5016      /* free fdir AU */
5017      image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
5018
5019      /* free ddr AU */
5020      image->abm[DDR_AU >> 3] &= ~ (1 << (DDR_AU & 7));
5021
5022      /* delete parent catalog entry */
5023      for (i=catalog_index; i<113; i++)
5024         catalog.subdirs[i] = catalog.subdirs[i+1];
5025      catalog.subdirs[114].dir_ptr = 0;
5026      catalog.num_subdirs--;
5027
5028      /* update parent VIB/DDR */
5029      if (read_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &ddr_buf))
5030         return IMGTOOLERR_READERROR;
5031      ddr_buf.num_subdirs = catalog.num_subdirs;
5032      for (i=0; i<114; i++)
5033         set_UINT16BE(&ddr_buf.subdir_AU[i], catalog.subdirs[i].dir_ptr);
5034      if (write_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &ddr_buf))
5035         return IMGTOOLERR_WRITEERROR;
5036
5037      /* save allocation bitmap (aphysrecs 1 through n, n<=33) */
5038      for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
5039         if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
5040            return IMGTOOLERR_WRITEERROR;
5041   }
5042   else
5043   {
5044      /* check integrity of FDR sibling chain, and go to last sibling */
5045      /* note that as we check that the back chain is consistent with the forward
5046      chain, we will also detect any cycle in the sibling chain, so we do not
5047      need to check against them explicitely */
5048      {
5049         int pastendoflist_flag;
5050         unsigned prevfdr_aphysrec;
5051
5052
5053         pastendoflist_flag = 0;
5054         cursibFDR_index = 0;
5055         curfdr_aphysrec = catalog.files[catalog_index].fdr_ptr * image->AUformat.physrecsperAU;
5056         if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
5057            return IMGTOOLERR_READERROR;
5058
5059         if (get_UINT16BE(fdr.prevsibFDR_AU) != 0)
5060            return IMGTOOLERR_CORRUPTIMAGE;
5061
5062         while (1)
5063         {
5064            if (! pastendoflist_flag)
5065            {
5066               /* look for end of list */
5067               for (i=0; i<54; i++)
5068               {
5069                  if (get_UINT16BE(fdr.clusters[i][0]) == 0)
5070                  {
5071                     endsibFDR_index = cursibFDR_index;
5072                     pastendoflist_flag = TRUE;
5073                     break;
5074                  }
5075               }
5076            }
5077
5078            /* exit loop if end of sibling chain */
5079            if (! get_UINT16BE(fdr.nextsibFDR_AU))
5080               break;
5081
5082            /* otherwise read next FDR */
5083            if (get_UINT16BE(fdr.nextsibFDR_AU) >= image->AUformat.totAUs)
5084               return IMGTOOLERR_CORRUPTIMAGE;
5085
5086            prevfdr_aphysrec = curfdr_aphysrec;
5087            curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(image, &fdr);
5088            if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
5089               return IMGTOOLERR_READERROR;
5090            cursibFDR_index++;
5091
5092            /* check that back chaining is consistent with forward chaining */
5093            if (get_win_fdr_prevsibFDR_aphysrec(image, &fdr) != prevfdr_aphysrec)
5094               return IMGTOOLERR_CORRUPTIMAGE;
5095         }
5096         if (! pastendoflist_flag)
5097            endsibFDR_index = cursibFDR_index;
5098      }
5099
5100
5101      while (1)
5102      {
5103         if (cursibFDR_index <= endsibFDR_index)
5104         {
5105
5106            for (i = 0; i < 54; i++)
5107            {
5108               cur_AU = get_UINT16BE(fdr.clusters[i][0]);
5109               if (cur_AU == 0)
5110                  /* end of cluster list */
5111                  break;
5112               end_AU = get_UINT16BE(fdr.clusters[i][1]);
5113
5114               while (cur_AU<=end_AU)
5115               {
5116                  /* the condition below is an error, but it should not prevent
5117                  us from deleting the file */
5118                  if (cur_AU >= image->AUformat.totAUs)
5119                     /*return IMGTOOLERR_CORRUPTIMAGE;*/
5120                     break;
5121
5122                  image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
5123
5124                  cur_AU++;
5125               }
5126            }
5127         }
5128
5129         /* free fdr AU if applicable */
5130         if ((curfdr_aphysrec % image->AUformat.physrecsperAU) == 0)
5131         {
5132            cur_AU = curfdr_aphysrec / image->AUformat.physrecsperAU;
5133            image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
5134         }
5135
5136         if (cursibFDR_index == 0)
5137            break;
5138         curfdr_aphysrec = get_win_fdr_prevsibFDR_aphysrec(image, &fdr);
5139         if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
5140            return IMGTOOLERR_READERROR;
5141         cursibFDR_index--;
5142      }
5143
5144
5145      /* delete catalog entry */
5146      for (i=catalog_index; i<127; i++)
5147         catalog.files[i] = catalog.files[i+1];
5148      catalog.files[127].fdr_ptr = 0;
5149      catalog.num_files--;
5150
5151
5152      /* update VIB/DDR and get FDIR AU address */
5153      {
5154         win_vib_ddr parent_ddr;
5155
5156         if (read_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &parent_ddr))
5157            return IMGTOOLERR_READERROR;
5158         parent_ddr.num_files = catalog.num_files;
5159         if (write_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &parent_ddr))
5160            return IMGTOOLERR_WRITEERROR;
5161         cur_AU = get_UINT16BE(parent_ddr.fdir_AU);
5162      }
5163
5164      /* generate FDIR and save it */
5165      for (i=0; i<127; i++)
5166      {
5167         buf[2*i] = catalog.files[i].fdr_ptr >> 8;
5168         buf[2*i+1] = catalog.files[i].fdr_ptr & 0xff;
5169      }
5170      buf[254] = parent_ddr_AU >> 8;
5171      buf[255] = parent_ddr_AU & 0xff;
5172      if (write_absolute_physrec(& image->l1_img, cur_AU * image->AUformat.physrecsperAU, buf))
5173         return IMGTOOLERR_WRITEERROR;
5174
5175      /* save allocation bitmap (aphysrecs 1 through n, n<=33) */
5176      for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
5177         if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
5178            return IMGTOOLERR_WRITEERROR;
5179   }
5180
5181   return 0;
5182}
5183
5184/*
5185   Create a blank ti99_image (common code).
5186
5187   Supports MESS and V9T9 formats only
5188*/
5189static imgtoolerr_t dsk_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions, ti99_img_format img_format)
5190{
5191   const char *volname;
5192   int density;
5193   ti99_lvl1_imgref l1_img;
5194   int protected;
5195
5196   int totphysrecs, physrecsperAU, totAUs;
5197
5198   dsk_vib vib;
5199   UINT8 empty_sec[256];
5200
5201   int i;
5202
5203   l1_img.img_format = img_format;
5204   l1_img.file_handle = f;
5205
5206   /* read options */
5207   volname = option_resolution_lookup_string(createoptions, dsk_createopts_volname);
5208   l1_img.geometry.heads = option_resolution_lookup_int(createoptions, dsk_createopts_sides);
5209   l1_img.geometry.cylinders = option_resolution_lookup_int(createoptions, dsk_createopts_tracks);
5210   l1_img.geometry.secspertrack = option_resolution_lookup_int(createoptions, dsk_createopts_sectors);
5211   protected = option_resolution_lookup_int(createoptions, dsk_createopts_protection);
5212   density = option_resolution_lookup_int(createoptions, dsk_createopts_density);
5213
5214   /* NPW 03-DEC-2003 - Fixes a crash if volname is NULL */
5215   if (!volname)
5216      volname = "";
5217
5218   totphysrecs = l1_img.geometry.secspertrack * l1_img.geometry.cylinders * l1_img.geometry.heads;
5219   physrecsperAU = (totphysrecs + 1599) / 1600;
5220   /* round to next larger power of 2 */
5221   for (i = 1; i < physrecsperAU; i <<= 1)
5222      ;
5223   physrecsperAU = i;
5224   totAUs = totphysrecs / physrecsperAU;
5225
5226   /* auto-density */
5227   if (density == 0)
5228   {
5229      if (l1_img.geometry.secspertrack <= 9)
5230         density = 1;
5231      else if (l1_img.geometry.secspertrack <= 18)
5232         density = 2;
5233      else
5234         density = 3;
5235   }
5236
5237   /* check volume name */
5238   if (strchr(volname, '.') || strchr(volname, ' ') || (strlen(volname) > 10))
5239      return /*IMGTOOLERR_BADFILENAME*/IMGTOOLERR_PARAMCORRUPT;
5240
5241   /* FM disks can hold fewer sector per track than MFM disks */
5242   if ((density == 1) && (l1_img.geometry.secspertrack > 9))
5243      return IMGTOOLERR_PARAMTOOLARGE;
5244
5245   /* DD disks can hold fewer sector per track than HD disks */
5246   if ((density == 2) && (l1_img.geometry.secspertrack > 18))
5247      return IMGTOOLERR_PARAMTOOLARGE;
5248
5249   /* check total disk size */
5250   if (totphysrecs < 2)
5251      return IMGTOOLERR_PARAMTOOSMALL;
5252
5253   /* initialize vib in aphysrec 0 */
5254
5255   /* set volume name */
5256   str_to_fname(vib.name, volname);
5257
5258   /* set every header field */
5259   set_UINT16BE(& vib.totphysrecs, totphysrecs);
5260   vib.secspertrack = l1_img.geometry.secspertrack;
5261   vib.id[0] = 'D';
5262   vib.id[1] = 'S';
5263   vib.id[2] = 'K';
5264   vib.protection = protected ? 'P' : ' ';
5265   vib.cylinders = l1_img.geometry.cylinders;
5266   vib.heads = l1_img.geometry.heads;
5267   vib.density = density;
5268   for (i=0; i<3; i++)
5269   {
5270      memset(vib.subdir[i].name, '\0', 10);
5271      set_UINT16BE(& vib.subdir[i].fdir_aphysrec, 0);
5272   }
5273
5274   /* clear bitmap */
5275   for (i=0; i < (totAUs>>3); i++)
5276      vib.abm[i] = 0;
5277
5278   if (totAUs & 7)
5279   {
5280      vib.abm[i] = 0xff << (totAUs & 7);
5281      i++;
5282   }
5283
5284   for (; i < 200; i++)
5285      vib.abm[i] = 0xff;
5286
5287   /* mark first 2 aphysrecs (vib and fdir) as used */
5288   vib.abm[0] |= (physrecsperAU == 1) ? 3 : 1;
5289
5290   /* write aphysrec 0 */
5291   if (write_absolute_physrec(& l1_img, 0, &vib))
5292      return IMGTOOLERR_WRITEERROR;
5293
5294
5295   /* now clear every other physrecs, including the FDIR record */
5296   memset(empty_sec, 0, 256);
5297
5298   for (i=1; i<totphysrecs; i++)
5299      if (write_absolute_physrec(& l1_img, i, empty_sec))
5300         return IMGTOOLERR_WRITEERROR;
5301
5302
5303   return dsk_image_init(image, f, img_format);
5304}
5305
5306/*
5307   Create a blank ti99_image (MESS format).
5308*/
5309static imgtoolerr_t dsk_image_create_mess(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions)
5310{
5311   return dsk_image_create(image, f, createoptions, if_mess);
5312}
5313
5314/*
5315   Create a blank ti99_image (V9T9 format).
5316*/
5317static imgtoolerr_t dsk_image_create_v9t9(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions)
5318{
5319   return dsk_image_create(image, f, createoptions, if_v9t9);
5320}
src/mess/tools/imgtool/pc_hard.c
r1339r1340
1/****************************************************************************
2
3   pc_hard.c
4
5   PC hard drives
6
7*****************************************************************************
8
9  Master boot record format:
10
11  Offset  Length  Description
12  ------  ------  -----------
13       0     446  Boot machine code
14     446      16  Partion #1 info
15     462      16  Partion #2 info
16     478      16  Partion #3 info
17     494      16  Partion #4 info
18    510       2  Magic bytes (0x55 0xAA)
19
20
21  Partition info format:
22
23  Offset  Length  Description
24  ------  ------  -----------
25       0       1  Bootable (0x80=bootable 0x00=not bootable)
26      1       1  Starting head
27      2       1  Starting sector (bits 5-0) and high bits of starting track (bits 6-5)
28      3       1  Low bits of starting track
29      4       1  Partition type:
30                   0x00      Unused
31                  0x?1      FAT12   (0-15 MB)
32                  0x?2      XENIX
33                  0x?4      FAT16   (16-32 MB)
34                  0x?6      FAT16`   (32 MB-2 GB)
35                  0x?7      HPFS or NTFS
36                  0x?A      Boot Manager
37                  0x?B      FAT32   (512 MB-2 TB)
38                  0x?C      FAT32   (512 MB-2 TB LBA)
39                  0x1?      OS/2 Boot manager/Win95 hidden
40                  0xC?      DR-DOS secured partition
41                  0xD?      Multiuser DOS secured partition
42                  0xE?      SpeedStor extended partition
43      5       1  Ending head
44      6       1  Ending sector (bits 5-0) and high bits of ending track (bits 6-5)
45      7       1  Low bits of ending track
46      8       4  Sector index of beginning of partition
47     12       4  Total sectors in partition
48
49****************************************************************************/
50
51#include "imgtool.h"
52#include "imghd.h"
53
54#define FAT_SECLEN   512
55
56OPTION_GUIDE_START( pc_chd_create_optionguide )
57   OPTION_INT('T', "cylinders",   "Cylinders" )
58   OPTION_INT('H', "heads",      "Heads" )
59   OPTION_INT('S', "sectors",      "Sectors" )
60OPTION_GUIDE_END
61
62static const char pc_chd_create_optionspec[] = "H1-[16]S1-[32]-63T10/20/30/40/50/60/70/80/90/[100]/110/120/130/140/150/160/170/180/190/200";
63
64static const char fat8_string[8]  = { 'F', 'A', 'T', ' ', ' ', ' ', ' ', ' ' };
65static const char fat12_string[8] = { 'F', 'A', 'T', '1', '2', ' ', ' ', ' ' };
66static const char fat16_string[8] = { 'F', 'A', 'T', '1', '6', ' ', ' ', ' ' };
67static const char fat32_string[8] = { 'F', 'A', 'T', '3', '2', ' ', ' ', ' ' };
68
69/* imports from fat.c */
70extern void fat_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info);
71
72
73typedef struct _pc_chd_image_info pc_chd_image_info;
74struct _pc_chd_image_info
75{
76   struct mess_hard_disk_file hard_disk;
77
78   struct
79   {
80      unsigned int corrupt : 1;
81      UINT8 partition_type;
82      UINT32 fat_bits;
83      UINT32 starting_track;
84      UINT32 starting_head;
85      UINT32 starting_sector;
86      UINT32 ending_track;
87      UINT32 ending_head;
88      UINT32 ending_sector;
89      UINT32 sector_index;
90      UINT32 total_sectors;
91   } partitions[4];
92};
93
94
95
96static pc_chd_image_info *pc_chd_get_image_info(imgtool_image *image)
97{
98   return (pc_chd_image_info *) imgtool_image_extra_bytes(image);
99}
100
101
102
103static void pc_chd_locate_block(imgtool_image *image, UINT64 block, UINT32 *cylinder, UINT32 *head, UINT32 *sector)
104{
105   pc_chd_image_info *info;
106   const hard_disk_info *hd_info;
107
108   info = pc_chd_get_image_info(image);
109   hd_info = imghd_get_header(&info->hard_disk);
110
111   *sector = block % hd_info->sectors;
112   *head = (block / hd_info->sectors) % hd_info->heads;
113   *cylinder = block / hd_info->sectors / hd_info->heads;
114}
115
116
117
118static imgtoolerr_t pc_chd_partition_create(imgtool_image *image, int partition_index, UINT64 first_block, UINT64 block_count)
119{
120   imgtoolerr_t err;
121   UINT8 header_block[FAT_SECLEN];
122   UINT8 partition_block[FAT_SECLEN];
123   UINT8 partition_type;
124   UINT8 *fat_type;
125   UINT8 *partition_entry;
126   UINT32 first_cylinder, first_head, first_sector;
127   UINT32 last_cylinder, last_head, last_sector;
128   imgtool_class imgclass = { fat_get_info };
129   imgtoolerr_t (*fat_partition_create)(imgtool_image *image, UINT64 first_block, UINT64 block_count);
130
131   /* sanity checks */
132   assert((partition_index >= 0) && (partition_index <= 3));
133
134   /* compute geometry */
135   pc_chd_locate_block(image, first_block, &first_cylinder, &first_head, &first_sector);
136   pc_chd_locate_block(image, first_block + block_count - 1, &last_cylinder, &last_head, &last_sector);
137
138   /* load fat_partition_create */
139   fat_partition_create = (imgtoolerr_t (*)(imgtool_image *, UINT64, UINT64))
140      imgtool_get_info_fct(&imgclass, IMGTOOLINFO_PTR_CREATE_PARTITION);
141
142   /* first create the actual partition */
143   err = fat_partition_create(image, first_block, block_count);
144   if (err)
145      goto done;
146
147   /* read the first block of the partition, to determine the type of FAT */
148   err = imgtool_image_read_block(image, first_block, partition_block);
149   if (err)
150      goto done;
151   fat_type = &partition_block[54];
152   if (!memcmp(fat_type, fat8_string, sizeof(fat8_string)))
153      partition_type = 0x01;
154   else if (!memcmp(fat_type, fat12_string, sizeof(fat12_string)))
155      partition_type = 0x01;
156   else if ((!memcmp(fat_type, fat16_string, sizeof(fat16_string))) && (block_count < 32*1024*1024/FAT_SECLEN))
157      partition_type = 0x04;
158   else if ((!memcmp(fat_type, fat16_string, sizeof(fat16_string))) && (block_count >= 32*1024*1024/FAT_SECLEN))
159      partition_type = 0x06;
160   else
161      partition_type = 0x0B;
162
163   /* read the partition header */
164   err = imgtool_image_read_block(image, 0, header_block);
165   if (err)
166      goto done;
167
168   /* fill out the partition entry */
169   partition_entry = &header_block[446 + (partition_index * 16)];
170   place_integer_le(partition_entry,  0, 1, 0x80);
171   place_integer_le(partition_entry,  1, 1, first_head);
172   place_integer_le(partition_entry,  2, 1, ((first_sector & 0x3F) | (first_cylinder >> 8 << 2)));
173   place_integer_le(partition_entry,  3, 1, first_cylinder);
174   place_integer_le(partition_entry,  4, 1, partition_type);
175   place_integer_le(partition_entry,  5, 1, last_head);
176   place_integer_le(partition_entry,  6, 1, ((last_sector & 0x3F) | (last_cylinder >> 8 << 2)));
177   place_integer_le(partition_entry,  7, 1, last_cylinder);
178   place_integer_le(partition_entry,  8, 4, first_block);
179   place_integer_le(partition_entry, 12, 4, block_count);
180
181   /* write the partition header */
182   err = imgtool_image_write_block(image, 0, header_block);
183   if (err)
184      goto done;
185
186done:
187   return err;
188}
189
190
191
192static imgtoolerr_t pc_chd_read_partition_header(imgtool_image *image)
193{
194   imgtoolerr_t err;
195   int i;
196   const UINT8 *partition_info;
197   pc_chd_image_info *info;
198   UINT8 buffer[FAT_SECLEN];
199
200   info = pc_chd_get_image_info(image);
201
202   /* read the initial block */
203   err = imgtool_image_read_block(image, 0, buffer);
204   if (err)
205      return err;
206
207   /* magic bytes present? */
208   if ((buffer[510] != 0x55) || (buffer[511] != 0xAA))
209      return IMGTOOLERR_CORRUPTIMAGE;
210
211   for (i = 0; i < sizeof(info->partitions) / sizeof(info->partitions[0]); i++)
212   {
213      partition_info = &buffer[446 + i * 16];
214
215      info->partitions[i].partition_type   = partition_info[4];
216      info->partitions[i].starting_head   = partition_info[1];
217      info->partitions[i].starting_track   = ((partition_info[2] << 2) & 0xFF00) | partition_info[3];
218      info->partitions[i].starting_sector   = partition_info[2] & 0x3F;
219      info->partitions[i].ending_head      = partition_info[5];
220      info->partitions[i].ending_track   = ((partition_info[6] << 2) & 0xFF00) | partition_info[7];
221      info->partitions[i].ending_sector   = partition_info[6] & 0x3F;
222
223      info->partitions[i].sector_index   = pick_integer_le(partition_info,  8, 4);
224      info->partitions[i].total_sectors   = pick_integer_le(partition_info, 12, 4);
225
226      if (info->partitions[i].starting_track > info->partitions[i].ending_track)
227         return IMGTOOLERR_CORRUPTIMAGE;
228   }
229   return IMGTOOLERR_SUCCESS;
230}
231
232
233
234static imgtoolerr_t pc_chd_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *opts)
235{
236   imgtoolerr_t err;
237   UINT32 cylinders, heads, sectors;
238   pc_chd_image_info *info;
239   UINT8 header_block[FAT_SECLEN];
240
241   cylinders = option_resolution_lookup_int(opts, 'T');
242   heads = option_resolution_lookup_int(opts, 'H');
243   sectors = option_resolution_lookup_int(opts, 'S');
244
245   info = pc_chd_get_image_info(image);
246
247   /* create the hard disk image */
248   err = imghd_create(f, 0, cylinders, heads, sectors, FAT_SECLEN);
249   if (err)
250      goto done;
251
252   err = imghd_open(f, &info->hard_disk);
253   if (err)
254      goto done;
255
256   /* set up partition header block */
257   memset(header_block, 0, sizeof(header_block));
258   header_block[510] = 0x55;
259   header_block[511] = 0xAA;
260   err = imgtool_image_write_block(image, 0, header_block);
261   if (err)
262      goto done;
263
264   err = pc_chd_partition_create(image, 0, 1, cylinders * heads * sectors - 1);
265   if (err)
266      goto done;
267
268   err = pc_chd_read_partition_header(image);
269   if (err)
270      goto done;
271
272done:
273   if (err)
274      imghd_close(&info->hard_disk);
275   return err;
276}
277
278
279
280static imgtoolerr_t pc_chd_image_open(imgtool_image *image, imgtool_stream *stream)
281{
282   imgtoolerr_t err;
283   pc_chd_image_info *info;
284
285   info = pc_chd_get_image_info(image);
286
287   /* open the hard drive */
288   err = imghd_open(stream, &info->hard_disk);
289   if (err)
290      return err;
291
292   err = pc_chd_read_partition_header(image);
293   if (err)
294      return err;
295
296   return IMGTOOLERR_SUCCESS;
297}
298
299
300
301static void pc_chd_image_close(imgtool_image *image)
302{
303   pc_chd_image_info *info;
304   info = pc_chd_get_image_info(image);
305   imghd_close(&info->hard_disk);
306}
307
308
309
310static imgtoolerr_t pc_chd_image_get_geometry(imgtool_image *image, UINT32 *tracks, UINT32 *heads, UINT32 *sectors)
311{
312   pc_chd_image_info *info;
313   const hard_disk_info *hd_info;
314
315   info = pc_chd_get_image_info(image);
316   hd_info = imghd_get_header(&info->hard_disk);
317
318   *tracks = hd_info->cylinders;
319   *heads = hd_info->heads;
320   *sectors = hd_info->sectors;
321   return IMGTOOLERR_SUCCESS;
322}
323
324
325
326static imgtoolerr_t   pc_chd_image_getsectorsize(imgtool_image *image, UINT32 track, UINT32 head, UINT32 sector, UINT32 *sector_size)
327{
328   pc_chd_image_info *info;
329   info = pc_chd_get_image_info(image);
330   *sector_size = imghd_get_header(&info->hard_disk)->sectorbytes;
331   return IMGTOOLERR_SUCCESS;
332}
333
334
335
336static UINT32 pc_chd_calc_lbasector(pc_chd_image_info *info, UINT32 track, UINT32 head, UINT32 sector)
337{
338   UINT32 lbasector;
339   const hard_disk_info *hd_info;
340
341   hd_info = imghd_get_header(&info->hard_disk);
342   lbasector = track;
343   lbasector *= hd_info->heads;
344   lbasector += head;
345   lbasector *= hd_info->sectors;
346   lbasector += sector;
347   return lbasector;
348}
349
350
351
352static imgtoolerr_t   pc_chd_image_readsector(imgtool_image *image, UINT32 track, UINT32 head, UINT32 sector, void *buffer, size_t len)
353{
354   pc_chd_image_info *info;
355   info = pc_chd_get_image_info(image);
356   return imghd_read(&info->hard_disk,
357      pc_chd_calc_lbasector(info, track, head, sector),
358      buffer);
359}
360
361
362
363static imgtoolerr_t   pc_chd_image_writesector(imgtool_image *image, UINT32 track, UINT32 head, UINT32 sector, const void *buffer, size_t len)
364{
365   pc_chd_image_info *info;
366   info = pc_chd_get_image_info(image);
367   return imghd_write(&info->hard_disk,
368      pc_chd_calc_lbasector(info, track, head, sector),
369      buffer);
370}
371
372
373
374static imgtoolerr_t pc_chd_image_readblock(imgtool_image *image, void *buffer, UINT64 block)
375{
376   pc_chd_image_info *info;
377   info = pc_chd_get_image_info(image);
378   return imghd_read(&info->hard_disk, block, buffer);
379}
380
381
382
383static imgtoolerr_t pc_chd_image_writeblock(imgtool_image *image, const void *buffer, UINT64 block)
384{
385   pc_chd_image_info *info;
386   info = pc_chd_get_image_info(image);
387   return imghd_write(&info->hard_disk, block, buffer);
388}
389
390
391
392static imgtoolerr_t pc_chd_list_partitions(imgtool_image *image, imgtool_partition_info *partitions, size_t len)
393{
394   pc_chd_image_info *info;
395   size_t i;
396
397   info = pc_chd_get_image_info(image);
398
399   for (i = 0; i < MIN(4, len); i++)
400   {
401      partitions[i].base_block   = info->partitions[i].sector_index;
402      partitions[i].block_count   = info->partitions[i].total_sectors;
403
404      switch(info->partitions[i].partition_type)
405      {
406         case 0x00:   /* Empty Partition */
407            partitions[i].get_info = NULL;
408            break;
409
410         case 0x01:   /* FAT12 */
411         case 0x04:   /* FAT16 (-32 MB) */
412         case 0x06:   /* FAT16 (32+ MB) */
413         case 0x0B:   /* FAT32 */
414         case 0x0C:   /* FAT32 (LBA Mapped) */
415         case 0x0E:   /* FAT16 (LBA Mapped) */
416         case 0x11:   /* OS/2 FAT12 */
417         case 0x14:   /* OS/2 FAT16 (-32 MB) */
418         case 0x16:   /* OS/2 FAT16 (32+ MB) */
419         case 0x1B:   /* Hidden Win95 FAT32 */
420         case 0x1C:   /* Hidden Win95 FAT32 (LBA Mapped) */
421         case 0x1D:   /* Hidden Win95 FAT16 (LBA Mapped) */
422         case 0xC1:   /* DR-DOS FAT12 */
423         case 0xC4:   /* DR-DOS FAT16 (-32 MB) */
424         case 0xC6:   /* DR-DOS FAT16 (32+ MB) */
425         case 0xD1:   /* Old Multiuser DOS FAT12 */
426         case 0xD4:   /* Old Multiuser DOS FAT16 (-32 MB) */
427         case 0xD6:   /* Old Multiuser DOS FAT16 (32+ MB) */
428            partitions[i].get_info = fat_get_info;
429            break;
430
431         default:
432            partitions[i].get_info = unknown_partition_get_info;
433            break;
434      }
435   }
436   return IMGTOOLERR_SUCCESS;
437}
438
439
440
441void pc_chd_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
442{
443   switch(state)
444   {
445      /* --- the following bits of info are returned as 64-bit signed integers --- */
446      case IMGTOOLINFO_INT_BLOCK_SIZE:               info->i = FAT_SECLEN; break;
447      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(pc_chd_image_info); break;
448      case IMGTOOLINFO_INT_TRACKS_ARE_CALLED_CYLINDERS:   info->i = 1; break;
449
450      /* --- the following bits of info are returned as NULL-terminated strings --- */
451      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "pc_chd"); break;
452      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "PC CHD disk image"); break;
453      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "chd"); break;
454      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:         strcpy(info->s = imgtool_temp_str(), pc_chd_create_optionspec); break;
455
456      /* --- the following bits of info are returned as pointers to data or functions --- */
457      case IMGTOOLINFO_PTR_CREATE:                  info->create = pc_chd_image_create; break;
458      case IMGTOOLINFO_PTR_OPEN:                     info->open = pc_chd_image_open; break;
459      case IMGTOOLINFO_PTR_CLOSE:                     info->close = pc_chd_image_close; break;
460      case IMGTOOLINFO_PTR_READ_SECTOR:               info->read_sector = pc_chd_image_readsector; break;
461      case IMGTOOLINFO_PTR_WRITE_SECTOR:               info->write_sector = pc_chd_image_writesector; break;
462      case IMGTOOLINFO_PTR_READ_BLOCK:               info->read_block = pc_chd_image_readblock; break;
463      case IMGTOOLINFO_PTR_WRITE_BLOCK:               info->write_block = pc_chd_image_writeblock; break;
464      case IMGTOOLINFO_PTR_GET_SECTOR_SIZE:            info->get_sector_size = pc_chd_image_getsectorsize; break;
465      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:         info->createimage_optguide = pc_chd_create_optionguide; break;
466      case IMGTOOLINFO_PTR_GET_GEOMETRY:               info->get_geometry = pc_chd_image_get_geometry; break;
467      case IMGTOOLINFO_PTR_LIST_PARTITIONS:            info->list_partitions = pc_chd_list_partitions; break;
468   }
469}
src/mess/tools/imgtool/fmsx_cas.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "formats/fmsx_cas.h"
6#include "imgtoolx.h"
7#include "utils.h"
8
9/*
10   MSX module
11
12   fMSX style .cas for the MSX. Converts them to .wav files. Uses the
13   mess/formats/fmsx_cas.[ch] files, for the actual conversion.
14*/
15
16typedef struct {
17   imgtool_image         base;
18   char         *file_name;
19   imgtool_stream          *file_handle;
20   int          size;
21   unsigned char   *data;
22   int          count;
23   } CAS_IMAGE;
24
25typedef struct
26   {
27   imgtool_directory    base;
28   CAS_IMAGE   *image;
29   int         index;
30   } CAS_ITERATOR;
31
32static int fmsx_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
33static void fmsx_cas_image_exit(imgtool_image *img);
34//static void fmsx_cas_image_info(imgtool_image *img, char *string, const int len);
35static int fmsx_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
36static int fmsx_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
37static void fmsx_cas_image_closeenum(imgtool_directory *enumeration);
38static int fmsx_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
39
40IMAGEMODULE(
41   fmsx_cas,
42   "fMSX style .cas file",            /* human readable name */
43   "cas",                        /* file extension */
44   NULL,                        /* crcfile */
45   NULL,                        /* crc system name */
46   NULL,                        /* eoln */
47   0,                           /* flags */
48   fmsx_cas_image_init,            /* init function */
49   fmsx_cas_image_exit,            /* exit function */
50   NULL,                        /* info function */
51   fmsx_cas_image_beginenum,         /* begin enumeration */
52   fmsx_cas_image_nextenum,         /* enumerate next */
53   fmsx_cas_image_closeenum,         /* close enumeration */
54   NULL,                        /* free space on image */
55   fmsx_cas_image_readfile,         /* read file */
56   NULL,/* write file */
57   NULL,/* delete file */
58   NULL,/* create image */
59   NULL,                        /* read sector */
60   NULL,                        /* write sector */
61   NULL,               /* file options */
62   NULL               /* create options */
63)
64
65static int fmsx_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
66   {
67   CAS_IMAGE *image;
68   int len;
69   char *pbase;
70   char default_name[] = "msxtape";
71
72   image = (CAS_IMAGE*)malloc (sizeof (CAS_IMAGE) );
73   if (!image) return IMGTOOLERR_OUTOFMEMORY;
74
75   *outimg = (imgtool_image*)image;
76
77   memset(image, 0, sizeof(CAS_IMAGE));
78   image->base.module = mod;
79   image->size=stream_size(f);
80   image->file_handle=f;
81
82    if (image->size < 9)
83      {
84      free (image);
85      return IMGTOOLERR_CORRUPTIMAGE;
86      }
87
88   image->data = (unsigned char *) malloc(image->size);
89   if (!image->data || (stream_read(f, image->data, image->size)!=image->size) )
90   {
91      free(image);
92      *outimg=NULL;
93      return IMGTOOLERR_OUTOFMEMORY;
94   }
95
96     if ( (image->count = fmsx_cas_to_wav_size (image->data, image->size) ) < 0)
97      {
98      free(image->data);
99      free(image);
100      *outimg=NULL;
101      return IMGTOOLERR_CORRUPTIMAGE;
102      }
103
104   pbase = NULL;
105    if (pbase) len = strlen (pbase);
106    else len = strlen (default_name);
107
108    image->file_name = malloc (len + 5);
109   if (!image->file_name)
110      {
111      free(image->data);
112      free(image);
113      *outimg=NULL;
114      return IMGTOOLERR_CORRUPTIMAGE;
115      }
116
117    if (!pbase)
118      strcpy (image->file_name, default_name);
119    else
120      {
121      strcpy (image->file_name, pbase);
122        if (len > 4)
123         if (!strncmpi (".cas", image->file_name + len - 4, 4) ) len -= 4;
124
125      strcpy (image->file_name + len, ".wav");
126      }
127
128   return 0;
129   }
130
131static void fmsx_cas_image_exit(imgtool_image *img)
132   {
133   CAS_IMAGE *image=(CAS_IMAGE*)img;
134   stream_close(image->file_handle);
135   free(image->file_name);
136   free(image->data);
137   free(image);
138   }
139
140static int fmsx_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
141{
142   CAS_IMAGE *image=(CAS_IMAGE*)img;
143   CAS_ITERATOR *iter;
144
145   iter=*(CAS_ITERATOR**)outenum = (CAS_ITERATOR*) malloc(sizeof(CAS_ITERATOR));
146   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
147
148   iter->base.module = img->module;
149
150   iter->image=image;
151   iter->index = 0;
152   return 0;
153}
154
155static int fmsx_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
156{
157   CAS_ITERATOR *iter=(CAS_ITERATOR*)enumeration;
158
159   ent->eof=iter->index;
160   if (!ent->eof)
161   {
162      strcpy (ent->fname, iter->image->file_name);
163      ent->corrupt=0;
164      ent->filesize = iter->image->count * 2 + 0x2c;
165      iter->index++;
166   }
167
168   return 0;
169}
170
171static void fmsx_cas_image_closeenum(imgtool_directory *enumeration)
172{
173   free(enumeration);
174}
175
176static int fmsx_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
177   {
178   CAS_IMAGE *image=(CAS_IMAGE*)img;
179   INT16 *wavdata;
180   UINT16   temp16;
181   UINT32   temp32;
182   int wavlen, offset, rc;
183
184   if (mame_stricmp (fname, image->file_name) )
185      return IMGTOOLERR_MODULENOTFOUND;
186
187   rc = fmsx_cas_to_wav(image->data, image->size, &wavdata, &wavlen);
188   if (rc == 2)
189      return IMGTOOLERR_OUTOFMEMORY;
190   else if (rc)
191      return IMGTOOLERR_CORRUPTIMAGE;
192
193   if (wavlen != image->count)
194      {
195      free (wavdata);
196      return IMGTOOLERR_UNEXPECTED;
197      }
198
199    /* write the core header for a WAVE file */
200   offset = stream_write(destf, "RIFF", 4);
201    if( offset < 4 )
202       {
203      free(wavdata);
204      return IMGTOOLERR_WRITEERROR;
205       }
206
207   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2 + 0x24);
208   offset += stream_write(destf, &temp32, 4);
209    if( offset < 8 )
210       {
211      free(wavdata);
212      return IMGTOOLERR_WRITEERROR;
213       }
214
215   /* read the RIFF file type and make sure it's a WAVE file */
216   offset += stream_write(destf, "WAVEfmt ", 8);
217   if( offset < 16 )
218       {
219      free(wavdata);
220      return IMGTOOLERR_WRITEERROR;
221      }
222
223    /* size of the following 'fmt ' fields */
224    offset += stream_write(destf, "\x10\x00\x00\x00", 4);
225   if( offset < 20 )
226       {
227      free(wavdata);
228      return IMGTOOLERR_WRITEERROR;
229      }
230
231   /* format: PCM */
232   temp16 = LITTLE_ENDIANIZE_INT16 (1);
233   offset += stream_write(destf, &temp16, 2);
234   if( offset < 22 )
235       {
236      free(wavdata);
237      return IMGTOOLERR_WRITEERROR;
238      }
239
240   /* channels: 1 (mono) */
241   temp16 = LITTLE_ENDIANIZE_INT16 (1);
242   offset += stream_write(destf, &temp16, 2);
243   if( offset < 24 )
244       {
245      free(wavdata);
246      return IMGTOOLERR_WRITEERROR;
247      }
248
249   /* sample rate */
250   temp32 = LITTLE_ENDIANIZE_INT32(22050);
251   offset += stream_write(destf, &temp32, 4);
252   if( offset < 24 )
253       {
254      free(wavdata);
255      return IMGTOOLERR_WRITEERROR;
256      }
257
258   /* byte rate */
259   temp32 = LITTLE_ENDIANIZE_INT32(22050 * 2);
260   offset += stream_write(destf, &temp32, 4);
261   if( offset < 28 )
262       {
263      free(wavdata);
264      return IMGTOOLERR_WRITEERROR;
265      }
266
267   /* block align (size of one `sample') */
268   temp16 = LITTLE_ENDIANIZE_INT16 (2);
269   offset += stream_write(destf, &temp16, 2);
270   if( offset < 30 )
271       {
272      free(wavdata);
273      return IMGTOOLERR_WRITEERROR;
274      }
275
276   /* block align */
277   temp16 = LITTLE_ENDIANIZE_INT16 (16);
278   offset += stream_write(destf, &temp16, 2);
279   if( offset < 32 )
280       {
281      free(wavdata);
282      return IMGTOOLERR_WRITEERROR;
283      }
284
285   /* 'data' tag */
286   offset += stream_write(destf, "data", 4);
287   if( offset < 36 )
288       {
289      free(wavdata);
290      return IMGTOOLERR_WRITEERROR;
291      }
292
293   /* data size */
294   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2);
295   offset += stream_write(destf, &temp32, 4);
296   if( offset < 40 )
297       {
298      free(wavdata);
299      return IMGTOOLERR_WRITEERROR;
300      }
301
302   if (stream_write(destf, wavdata, (image->count*2))!=(image->count*2))
303       {
304      free(wavdata);
305      return IMGTOOLERR_WRITEERROR;
306      }
307
308   free (wavdata);
309
310   return 0;
311   }
312
src/mess/tools/imgtool/rom16.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "zlib.h"
5#include "osdepend.h"
6#include "imgtoolx.h"
7
8typedef struct {
9   imgtool_image base;
10   imgtool_stream *file_handle;
11   int size;
12   int modified;
13   unsigned char *data;
14} rom16_image;
15
16typedef struct {
17   imgtool_directory base;
18   rom16_image *image;
19   int index;
20} rom16_iterator;
21
22static int rom16_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
23static void rom16_image_exit(imgtool_image *img);
24//static void rom16_image_info(imgtool_image *img, char *string, const int len);
25static int rom16_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
26static int rom16_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
27static void rom16_image_closeenum(imgtool_directory *enumeration);
28static int rom16_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
29static int rom16_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
30//static int rom16_image_create(imgtool_stream *f, const geometry_options *options_);
31
32IMAGEMODULE(
33   rom16,
34   "16 bit wide Romimage",   /* human readable name */
35   "rom",                        /* file extension */
36   NULL,                        /* crcfile */
37   NULL,                        /* crc system name */
38   NULL,                        /* eoln */
39   0,                           /* flags */
40   rom16_image_init,            /* init function */
41   rom16_image_exit,            /* exit function */
42   NULL, /* info function */
43   rom16_image_beginenum,         /* begin enumeration */
44   rom16_image_nextenum,         /* enumerate next */
45   rom16_image_closeenum,         /* close enumeration */
46   NULL, //crt_image_freespace,         /* free space on image */
47   rom16_image_readfile,         /* read file */
48   rom16_image_writefile,         /* write file */
49   NULL,         /* delete file */
50   NULL,//   rom16_image_create,            /* create image */
51   NULL,
52   NULL,
53   NULL,                     /* file options */
54   NULL                     /* create options */
55)
56
57static int rom16_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
58{
59   rom16_image *image;
60
61   image=*(rom16_image**)outimg=(rom16_image *) malloc(sizeof(rom16_image));
62   if (!image) return IMGTOOLERR_OUTOFMEMORY;
63
64   memset(image, 0, sizeof(rom16_image));
65   image->base.module = mod;
66   image->size=stream_size(f);
67   image->file_handle=f;
68
69   image->data = (unsigned char *) malloc(image->size);
70   if ( (!image->data)
71       ||(stream_read(f, image->data, image->size)!=image->size) ) {
72      free(image);
73      *outimg=NULL;
74      return IMGTOOLERR_OUTOFMEMORY;
75   }
76
77   return 0;
78}
79
80static void rom16_image_exit(imgtool_image *img)
81{
82   rom16_image *image=(rom16_image*)img;
83   if (image->modified) {
84      stream_clear(image->file_handle);
85      stream_write(image->file_handle, image->data, image->size);
86   }
87   stream_close(image->file_handle);
88   free(image->data);
89   free(image);
90}
91
92#if 0
93static void rom16_image_info(imgtool_image *img, char *string, const int len)
94{
95   _image *image=(rom16_image*)img;
96   sprintf(string, "%-32s\nversion:%.4x type:%d:%s exrom:%d game:%d",
97         HEADER(image)->name,
98         GET_UWORD(HEADER(image)->version),
99         GET_UWORD(HEADER(image)->hardware_type),
100         hardware_types[GET_UWORD(HEADER(image)->hardware_type)],
101         HEADER(image)->exrom_line, HEADER(image)->game_line);
102   return;
103}
104#endif
105
106static int rom16_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
107{
108   rom16_image *image=(rom16_image*)img;
109   rom16_iterator *iter;
110
111   iter=*(rom16_iterator**)outenum = (rom16_iterator *) malloc(sizeof(rom16_iterator));
112   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
113
114   iter->base.module = img->module;
115
116   iter->image=image;
117   iter->index = 0;
118   return 0;
119}
120
121static int rom16_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
122{
123    int pos = 0;
124   rom16_iterator *iter=(rom16_iterator*)enumeration;
125
126   ent->corrupt=0;
127   ent->eof=0;
128
129   switch (iter->index) {
130   case 0:
131       pos=0;
132       strcpy(ent->fname,"even");
133       ent->filesize= iter->image->size/2;
134       iter->index++;
135       break;
136   case 1:
137       pos=1;
138       iter->index++;
139       ent->filesize= iter->image->size/2;
140       strcpy(ent->fname,"odd");
141       break;
142   default:
143       ent->eof=1;
144   }
145   if (ent->eof==0 && ent->attr) {
146       unsigned crc=0;
147       for (;pos<iter->image->size; pos+=2) {
148      crc=crc32(crc, iter->image->data+pos, 1);
149       }
150       sprintf(ent->attr, "0x%x", crc);
151   }
152   return 0;
153}
154
155static void rom16_image_closeenum(imgtool_directory *enumeration)
156{
157   free(enumeration);
158}
159
160static int rom16_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
161{
162   rom16_image *image=(rom16_image*)img;
163   int pos;
164   int i;
165
166   if (mame_stricmp(fname, "even")==0) {
167      pos=0;
168   } else if (mame_stricmp(fname,"odd")==0) {
169      pos=1;
170   } else {
171      return IMGTOOLERR_MODULENOTFOUND;
172   }
173
174   for (i=0; i<image->size; i+=2) {
175      if (stream_write(destf, image->data+pos+i, 1)!=1)
176         return IMGTOOLERR_WRITEERROR;
177   }
178
179   return 0;
180}
181
182static int rom16_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef,
183                        const ResolvedOption *options_)
184{
185   rom16_image *image=(rom16_image*)img;
186   int size;
187   int pos;
188   int i;
189
190   size=stream_size(sourcef);
191   if (size*2!=image->size) return IMGTOOLERR_READERROR;
192   if (mame_stricmp(fname, "even")==0) {
193      pos=0;
194   } else if (mame_stricmp(fname,"odd")==0) {
195      pos=1;
196   } else {
197      return IMGTOOLERR_MODULENOTFOUND;
198   }
199
200   for (i=0; i<size; i++) {
201      if (stream_read(sourcef, image->data+pos+i*2, 1)!=1)
202         return IMGTOOLERR_READERROR;
203   }
204   image->modified=1;
205
206   return 0;
207}
208
209#if 0
210static int rom16_image_create(imgtool_stream *f, const ResolvedOption *options_)
211{
212//   if (options_->label) strcpy(header.name, options->label);
213   return (stream_write(f, &header, sizeof(crt_header)) == sizeof(crt_header))
214      ? 0 : IMGTOOLERR_WRITEERROR;
215}
216#endif
src/mess/tools/imgtool/cococas.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6#include "formats/cococas.h"
7#include "utils.h"
8
9static int cococas_initalt(imgtool_stream *instream, imgtool_stream **outstream, int *basepos,
10   int *length, int *channels, int *frequency, int *resolution);
11static int cococas_nextfile(imgtool_image *img, imgtool_dirent *ent);
12static int cococas_readfile(imgtool_image *img, imgtool_stream *destf);
13
14static UINT8 blockheader[] = { 0x55, 0x3C };
15
16WAVEMODULE(
17   cococas,
18   "Tandy CoCo Cassette",
19   "wav",
20   "\r",
21   IMGMODULE_FLAG_FILENAMES_PREFERUCASE,
22   1200, 1600, 2400,                  /* 0=1200 Hz, 1=2400 Hz, threshold=1600 Hz */
23   WAVEIMAGE_LSB_FIRST,
24   blockheader, sizeof(blockheader) / sizeof(blockheader[0]),
25   cococas_initalt,                  /* alternate initializer */
26   cococas_nextfile,                  /* enumerate next */
27   cococas_readfile                  /* read file */
28)
29
30typedef struct {
31   UINT8 type;
32   UINT8 length;
33   UINT8 data[255];
34} casblock;
35
36enum {
37   COCOCAS_FILETYPE_BASIC = 0,
38   COCOCAS_FILETYPE_DATA = 1,
39   COCOCAS_FILETYPE_BIN = 2
40};
41
42enum {
43   COCOCAS_BLOCKTYPE_FILENAME = 0,
44   COCOCAS_BLOCKTYPE_DATA = 1,
45   COCOCAS_BLOCKTYPE_EOF = 0xff
46};
47
48static int readblock(imgtool_image *img, casblock *blk)
49{
50   int err;
51   int i;
52   UINT8 sum = 0;
53   UINT8 actualsum;
54
55   /* Move forward until we hit header */
56   err = imgwave_forward(img);
57   if (err)
58      return err;
59
60   /* Read in the block type and length */
61   err = imgwave_read(img, &blk->type, 2);
62   if (err)
63      return err;
64   sum += blk->type;
65   sum += blk->length;
66
67   /* Read in the block data */
68   err = imgwave_read(img, blk->data, blk->length);
69   if (err)
70      return err;
71
72   /* Calculate checksum */
73   for (i = 0; i < blk->length; i++)
74      sum += blk->data[i];
75
76   /* Read the checksum */
77   err = imgwave_read(img, &actualsum, 1);
78   if (err)
79      return err;
80
81   if (sum != actualsum)
82      return IMGTOOLERR_CORRUPTIMAGE;
83
84   return 0;
85}
86
87static int cococas_nextfile(imgtool_image *img, imgtool_dirent *ent)
88{
89   int err, filesize;
90   casblock blk;
91   char fname[9];
92
93   /* Read directory block */
94   err = readblock(img, &blk);
95   if (err == IMGTOOLERR_INPUTPASTEND) {
96      ent->eof = 1;
97      return 0;
98   }
99   if (err)
100      return err;
101   
102   /* If block is not a filename block, fail */
103   if (blk.type != COCOCAS_BLOCKTYPE_FILENAME)
104      return IMGTOOLERR_CORRUPTIMAGE;
105
106   fname[8] = '\0';
107   memcpy(fname, blk.data, 8);
108   rtrim(fname);
109
110   if (strlen(fname) >= ent->fname_len)
111      return IMGTOOLERR_BUFFERTOOSMALL;
112   strcpy(ent->fname, fname);
113
114   filesize = 0;
115
116   do {
117      err = readblock(img, &blk);
118      if (err)
119         return err;
120
121      if (blk.type == COCOCAS_BLOCKTYPE_DATA) {
122         filesize += blk.length;
123      }
124   }
125   while(blk.type == COCOCAS_BLOCKTYPE_DATA);
126
127   if (blk.type != COCOCAS_BLOCKTYPE_EOF)
128      return IMGTOOLERR_CORRUPTIMAGE;
129   
130   ent->filesize = filesize;
131
132   return 0;
133}
134
135static int cococas_readfile(imgtool_image *img, imgtool_stream *destf)
136{
137   int err;
138   casblock blk;
139
140   /* Read directory block */
141   err = readblock(img, &blk);
142   if (err)
143      return err;
144   
145   /* If block is not a filename block, fail */
146   if (blk.type != COCOCAS_BLOCKTYPE_FILENAME)
147      return IMGTOOLERR_CORRUPTIMAGE;
148
149   do {
150      err = readblock(img, &blk);
151      if (err)
152         return err;
153
154      if (blk.type == COCOCAS_BLOCKTYPE_DATA)
155         stream_write(destf, blk.data, blk.length);
156   }
157   while(blk.type == COCOCAS_BLOCKTYPE_DATA);
158
159   if (blk.type != COCOCAS_BLOCKTYPE_EOF)
160      return IMGTOOLERR_CORRUPTIMAGE;
161   
162   return 0;
163}
164
165static int cococas_initalt(imgtool_stream *instream, imgtool_stream **outstream, int *basepos,
166   int *length, int *channels, int *frequency, int *resolution)
167{
168   int caslength;
169   int numsamples;
170   int samplepos;
171   UINT8 *bytes = NULL;
172   INT16 *buffer = NULL;
173   INT16 *newbuffer;
174
175   caslength = stream_size(instream);
176   bytes = malloc(caslength);
177   if (!bytes)
178      goto outofmemory;
179   stream_read(instream, bytes, caslength);
180
181   numsamples = COCO_WAVESAMPLES_HEADER + COCO_WAVESAMPLES_TRAILER + (caslength * 8*8);
182
183   buffer = malloc(numsamples * sizeof(INT16));
184   if (!buffer)
185      goto outofmemory;
186
187   coco_wave_size = caslength;
188
189   samplepos = 0;
190   samplepos += coco_cassette_fill_wave(&buffer[samplepos], COCO_WAVESAMPLES_HEADER, CODE_HEADER);
191   samplepos += coco_cassette_fill_wave(&buffer[samplepos], caslength, bytes);
192   samplepos += coco_cassette_fill_wave(&buffer[samplepos], COCO_WAVESAMPLES_TRAILER, CODE_TRAILER);
193
194   free(bytes);
195   bytes = NULL;
196
197   newbuffer = realloc(buffer, samplepos * sizeof(INT16));
198   if (!newbuffer)
199      goto outofmemory;
200   buffer = newbuffer;
201
202   *outstream = stream_open_mem(buffer, samplepos * sizeof(INT16));
203   if (!(*outstream))
204      goto outofmemory;
205
206   *basepos = 0;
207   *length = samplepos * 2;
208   *channels = 1;
209   *frequency = 4800;
210   *resolution = 16;
211   return 0;
212
213outofmemory:
214   if (bytes)
215      free(bytes);
216   if (buffer)
217      free(buffer);
218   return IMGTOOLERR_OUTOFMEMORY;
219}
220
221
222
src/mess/tools/imgtool/os9.c
r1339r1340
1/****************************************************************************
2
3   os9.c
4
5   CoCo OS-9 disk images
6
7****************************************************************************/
8
9#include <time.h>
10
11#include "imgtool.h"
12#include "formats/coco_dsk.h"
13#include "iflopimg.h"
14
15typedef enum
16{
17   CREATE_NONE,
18   CREATE_FILE,
19   CREATE_DIR
20} creation_policy_t;
21
22typedef struct _os9_diskinfo os9_diskinfo;
23struct _os9_diskinfo
24{
25   UINT32 total_sectors;
26   UINT32 sectors_per_track;
27   UINT32 allocation_bitmap_bytes;
28   UINT32 cluster_size;
29   UINT32 root_dir_lsn;
30   UINT32 owner_id;
31   UINT32 attributes;
32   UINT32 disk_id;
33   UINT32 format_flags;
34   UINT32 bootstrap_lsn;
35   UINT32 bootstrap_size;
36   UINT32 sector_size;
37
38   unsigned int sides : 2;
39   unsigned int double_density : 1;
40   unsigned int double_track : 1;
41   unsigned int quad_track_density : 1;
42   unsigned int octal_track_density : 1;
43
44   char name[33];
45   UINT8 *allocation_bitmap;
46};
47
48
49struct os9_fileinfo
50{
51   unsigned int directory : 1;
52   unsigned int non_sharable : 1;
53   unsigned int public_execute : 1;
54   unsigned int public_write : 1;
55   unsigned int public_read : 1;
56   unsigned int user_execute : 1;
57   unsigned int user_write : 1;
58   unsigned int user_read : 1;
59
60   UINT32 lsn;
61   UINT32 owner_id;
62   UINT32 link_count;
63   UINT32 file_size;
64
65   struct
66   {
67      UINT32 lsn;
68      UINT32 count;
69   } sector_map[48];
70};
71
72
73struct os9_direnum
74{
75   struct os9_fileinfo dir_info;
76   UINT32 index;
77};
78
79
80
81static void pick_string(const void *ptr, size_t offset, size_t length, char *dest)
82{
83   UINT8 b;
84
85   while(length--)
86   {
87      b = ((UINT8 *) ptr)[offset++];
88      *(dest++) = b & 0x7F;
89      if (b & 0x80)
90         length = 0;
91   }
92   *dest = '\0';
93}
94
95
96
97static void place_string(void *ptr, size_t offset, size_t length, const char *s)
98{
99   size_t i;
100   UINT8 b;
101   UINT8 *bptr;
102
103   bptr = (UINT8 *) ptr;
104   bptr += offset;
105
106   bptr[0] = 0x80;
107
108   for (i = 0; s[i] && (i < length); i++)
109   {
110      b = ((UINT8) s[i]) & 0x7F;
111      if (s[i+1] == '\0')
112         b |= 0x80;
113      bptr[i] = b;
114   }
115}
116
117
118
119static os9_diskinfo *os9_get_diskinfo(imgtool_image *image)
120{
121   return (os9_diskinfo *) imgtool_floppy_extrabytes(image);
122}
123
124
125
126static struct os9_direnum *os9_get_dirinfo(imgtool_directory *directory)
127{
128   return (struct os9_direnum *) imgtool_directory_extrabytes(directory);
129}
130
131
132
133static imgtoolerr_t os9_locate_lsn(imgtool_image *image, UINT32 lsn, UINT32 *head, UINT32 *track, UINT32 *sector)
134{
135   const os9_diskinfo *disk_info;
136
137   disk_info = os9_get_diskinfo(image);
138   if (lsn > disk_info->total_sectors)
139      return IMGTOOLERR_CORRUPTIMAGE;
140
141   *track = lsn / (disk_info->sectors_per_track * disk_info->sides);
142   *head = (lsn / disk_info->sectors_per_track) % disk_info->sides;
143   *sector = (lsn % disk_info->sectors_per_track) + 1;
144   return IMGTOOLERR_SUCCESS;
145}
146
147
148
149static imgtoolerr_t os9_read_lsn(imgtool_image *img, UINT32 lsn, int offset, void *buffer, size_t buffer_len)
150{
151   imgtoolerr_t err;
152   floperr_t ferr;
153   UINT32 head, track, sector;
154
155   err = os9_locate_lsn(img, lsn, &head, &track, &sector);
156   if (err)
157      return err;
158
159   ferr = floppy_read_sector(imgtool_floppy(img), head, track, sector, offset, buffer, buffer_len);
160   if (ferr)
161      return imgtool_floppy_error(ferr);
162
163   return IMGTOOLERR_SUCCESS;
164}
165
166
167
168static imgtoolerr_t os9_write_lsn(imgtool_image *img, UINT32 lsn, int offset, const void *buffer, size_t buffer_len)
169{
170   imgtoolerr_t err;
171   floperr_t ferr;
172   UINT32 head, track, sector;
173
174   err = os9_locate_lsn(img, lsn, &head, &track, &sector);
175   if (err)
176      return err;
177
178   ferr = floppy_write_sector(imgtool_floppy(img), head, track, sector, offset, buffer, buffer_len);
179   if (ferr)
180      return imgtool_floppy_error(ferr);
181
182   return IMGTOOLERR_SUCCESS;
183}
184
185
186
187static UINT32 os9_lookup_lsn(imgtool_image *img,
188   const struct os9_fileinfo *file_info, UINT32 *index)
189{
190   int i;
191   UINT32 lsn;
192   const os9_diskinfo *disk_info;
193
194   disk_info = os9_get_diskinfo(img);
195   lsn = *index / disk_info->sector_size;
196
197   i = 0;
198   while(lsn >= file_info->sector_map[i].count)
199      lsn -= file_info->sector_map[i++].count;
200
201   lsn = file_info->sector_map[i].lsn + lsn;
202   *index %= disk_info->sector_size;
203   return lsn;
204}
205
206
207
208static int os9_interpret_dirent(void *entry, char **filename, UINT32 *lsn, int *corrupt)
209{
210   int i;
211   char *entry_b = (char *) entry;
212
213   *filename = NULL;
214   *lsn = 0;
215   if (corrupt)
216      *corrupt = FALSE;
217
218   if (entry_b[28] != '\0')
219   {
220      if (corrupt)
221         *corrupt = TRUE;
222   }
223
224   for (i = 0; (i < 28) && !(entry_b[i] & 0x80); i++)
225      ;
226   entry_b[i] &= 0x7F;
227   entry_b[i+1] = '\0';
228
229   *lsn = pick_integer_be(entry, 29, 3);
230   if (strcmp(entry_b, ".") && strcmp(entry_b, ".."))
231      *filename = entry_b;
232   return *filename != NULL;
233}
234
235
236
237/*-------------------------------------------------
238    os9_decode_file_header - reads a file/directory
239   entry from an LSN, and decodes it
240-------------------------------------------------*/
241
242static imgtoolerr_t os9_decode_file_header(imgtool_image *image,
243   int lsn, struct os9_fileinfo *info)
244{
245   imgtoolerr_t err;
246   UINT32 attributes, count;
247   int max_entries, i;
248   const os9_diskinfo *disk_info;
249   UINT8 header[256];
250
251   disk_info = os9_get_diskinfo(image);
252
253   err = os9_read_lsn(image, lsn, 0, header, sizeof(header));
254   if (err)
255      return err;
256
257   info->lsn            = lsn;
258   attributes            = pick_integer_be(header, 0, 1);
259   info->owner_id         = pick_integer_be(header, 1, 2);
260   info->link_count      = pick_integer_be(header, 8, 1);
261   info->file_size         = pick_integer_be(header, 9, 4);
262   info->directory         = (attributes & 0x80) ? 1 : 0;
263   info->non_sharable      = (attributes & 0x40) ? 1 : 0;
264   info->public_execute   = (attributes & 0x20) ? 1 : 0;
265   info->public_write      = (attributes & 0x10) ? 1 : 0;
266   info->public_read      = (attributes & 0x08) ? 1 : 0;
267   info->user_execute      = (attributes & 0x04) ? 1 : 0;
268   info->user_write      = (attributes & 0x02) ? 1 : 0;
269   info->user_read         = (attributes & 0x01) ? 1 : 0;
270
271   if (info->directory && (info->file_size % 32 != 0))
272      return IMGTOOLERR_CORRUPTIMAGE;
273
274   /* read all sector map entries */
275   max_entries = (disk_info->sector_size - 16) / 5;
276   max_entries = MIN(max_entries, sizeof(info->sector_map) / sizeof(info->sector_map[0]) - 1);
277   for (i = 0; i < max_entries; i++)
278   {
279      lsn = pick_integer_be(header, 16 + (i * 5) + 0, 3);
280      count = pick_integer_be(header, 16 + (i * 5) + 3, 2);
281      if (count <= 0)
282         break;
283
284      info->sector_map[i].lsn = lsn;
285      info->sector_map[i].count = count;
286   }
287   info->sector_map[i].lsn = 0;
288   info->sector_map[i].count = 0;
289   return IMGTOOLERR_SUCCESS;
290}
291
292
293
294static imgtoolerr_t os9_allocate_lsn(imgtool_image *image, UINT32 *lsn)
295{
296   UINT32 i;
297   os9_diskinfo *disk_info;
298   UINT8 b, mask;
299
300   disk_info = os9_get_diskinfo(image);
301
302   for (i = 0; i < disk_info->total_sectors; i++)
303   {
304      b = disk_info->allocation_bitmap[i / 8];
305      mask = 1 << (7 - (i % 8));
306
307      if ((b & mask) == 0)
308      {
309         disk_info->allocation_bitmap[i / 8] |= mask;
310         *lsn = i;
311         return os9_write_lsn(image, 1, 0, disk_info->allocation_bitmap, disk_info->allocation_bitmap_bytes);
312      }
313   }
314   return IMGTOOLERR_NOSPACE;
315}
316
317
318
319static imgtoolerr_t os9_deallocate_lsn(imgtool_image *image, UINT32 lsn)
320{
321   UINT8 mask;
322   os9_diskinfo *disk_info;
323
324   disk_info = os9_get_diskinfo(image);
325   mask = 1 << (7 - (lsn % 8));
326   disk_info->allocation_bitmap[lsn / 8] &= ~mask;
327   return os9_write_lsn(image, 1, 0, disk_info->allocation_bitmap, disk_info->allocation_bitmap_bytes);
328}
329
330
331
332static UINT32 os9_get_free_lsns(imgtool_image *image)
333{
334   const os9_diskinfo *disk_info;
335   UINT32 i, free_lsns;
336   UINT8 b;
337
338   disk_info = os9_get_diskinfo(image);
339   free_lsns = 0;
340
341   for (i = 0; i < disk_info->total_sectors; i++)
342   {
343      b = disk_info->allocation_bitmap[i / 8];
344      b >>= (7 - (i % 8));
345      free_lsns += ~b & 1;
346   }
347
348   return free_lsns;
349}
350
351   
352
353static imgtoolerr_t os9_corrupt_file_error(const struct os9_fileinfo *file_info)
354{
355   imgtoolerr_t err;
356   if (file_info->directory)
357      err = IMGTOOLERR_CORRUPTDIR;
358   else
359      err = IMGTOOLERR_CORRUPTFILE;
360   return err;
361}
362
363
364
365static imgtoolerr_t os9_set_file_size(imgtool_image *image,
366   struct os9_fileinfo *file_info, UINT32 new_size)
367{
368   imgtoolerr_t err;
369   const os9_diskinfo *disk_info;
370   UINT32 new_lsn_count, current_lsn_count;
371   UINT32 free_lsns, lsn, i;
372   int sector_map_length = -1;
373   UINT8 header[256];
374
375   /* easy way out? */
376   if (file_info->file_size == new_size)
377      return IMGTOOLERR_SUCCESS;
378
379   disk_info = os9_get_diskinfo(image);
380
381   free_lsns = os9_get_free_lsns(image);
382   current_lsn_count = (file_info->file_size + disk_info->sector_size - 1) / disk_info->sector_size;
383   new_lsn_count = (new_size + disk_info->sector_size - 1) / disk_info->sector_size;
384
385   /* check to see if the file is growing and we do not have enough space */
386   if ((new_lsn_count > current_lsn_count) && (new_lsn_count - current_lsn_count > free_lsns))
387      return IMGTOOLERR_NOSPACE;
388
389   if (current_lsn_count != new_lsn_count)
390   {
391      /* first find out the size of our sector map */
392      sector_map_length = 0;
393      lsn = 0;
394      while((lsn < current_lsn_count) && (sector_map_length < sizeof(file_info->sector_map) / sizeof(file_info->sector_map[0])))
395      {
396         if (file_info->sector_map[sector_map_length].count == 0)
397            return os9_corrupt_file_error(file_info);
398
399         lsn += file_info->sector_map[sector_map_length].count;
400         sector_map_length++;
401      }
402
403      /* keep in mind that the sector_map might not parallel our expected
404       * current LSN count; we should tolerate this abnormality */
405      current_lsn_count = lsn;
406
407      while(current_lsn_count > new_lsn_count)
408      {
409         /* shrink this file */
410         lsn = file_info->sector_map[sector_map_length - 1].lsn +
411            file_info->sector_map[sector_map_length - 1].count - 1;
412
413         err = os9_deallocate_lsn(image, lsn);
414         if (err)
415            return err;
416
417         file_info->sector_map[sector_map_length - 1].count--;
418         while(sector_map_length > 0 && (file_info->sector_map[sector_map_length - 1].count == 0))
419            sector_map_length--;
420         current_lsn_count--;
421      }
422
423      while(current_lsn_count < new_lsn_count)
424      {
425         /* grow this file */
426         err = os9_allocate_lsn(image, &lsn);
427         if (err)
428            return err;
429
430         if ((sector_map_length > 0) && ((file_info->sector_map[sector_map_length - 1].lsn +
431            file_info->sector_map[sector_map_length - 1].count) == lsn))
432         {
433            file_info->sector_map[sector_map_length - 1].count++;
434         }
435         else if (sector_map_length >= sizeof(file_info->sector_map) / sizeof(file_info->sector_map[0]))
436         {
437            return IMGTOOLERR_NOSPACE;
438         }
439         else
440         {
441            file_info->sector_map[sector_map_length].lsn = lsn;
442            file_info->sector_map[sector_map_length].count = 1;
443            sector_map_length++;
444            file_info->sector_map[sector_map_length].lsn = 0;
445            file_info->sector_map[sector_map_length].count = 0;
446         }
447         current_lsn_count++;
448      }
449   }
450
451   /* now lets write back the sector */
452   err = os9_read_lsn(image, file_info->lsn, 0, header, sizeof(header));
453   if (err)
454      return err;
455
456   file_info->file_size = new_size;
457   place_integer_be(header, 9, 4, file_info->file_size);
458
459   /* do we have to write the sector map? */
460   if (sector_map_length >= 0)
461   {
462      for (i = 0; i < MIN(sector_map_length + 1, sizeof(file_info->sector_map) / sizeof(file_info->sector_map[0])); i++)
463      {
464         place_integer_be(header, 16 + (i * 5) + 0, 3, file_info->sector_map[i].lsn);
465         place_integer_be(header, 16 + (i * 5) + 3, 2, file_info->sector_map[i].count);
466      }
467   }
468
469   err = os9_write_lsn(image, file_info->lsn, 0, header, disk_info->sector_size);
470   if (err)
471      return err;
472
473   return IMGTOOLERR_SUCCESS;
474}
475
476
477
478/*-------------------------------------------------
479    os9_lookup_path - walks an OS-9 directory
480   structure to find a file, or optionally, create
481   a file
482-------------------------------------------------*/
483
484static imgtoolerr_t os9_lookup_path(imgtool_image *img, const char *path,
485   creation_policy_t create, struct os9_fileinfo *file_info,
486   UINT32 *parent_lsn, UINT32 *dirent_lsn, UINT32 *dirent_index)
487{
488   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
489   struct os9_fileinfo dir_info;
490   UINT32 index, current_lsn, dir_size;
491   UINT32 entry_index = 0;
492   UINT32 free_entry_index = 0xffffffff;
493   UINT32 entry_lsn = 0;
494   UINT32 allocated_lsn = 0;
495   UINT8 entry[32];
496   UINT8 block[64];
497   char *filename;
498   const os9_diskinfo *disk_info;
499
500   disk_info = os9_get_diskinfo(img);
501   current_lsn = disk_info->root_dir_lsn;
502
503   if (parent_lsn)
504      *parent_lsn = 0;
505
506   /* we have to transverse each path element */
507   while(*path)
508   {
509      if (parent_lsn)
510         *parent_lsn = current_lsn;
511
512      /* decode the directory header of this directory */
513      err = os9_decode_file_header(img, current_lsn, &dir_info);
514      if (err)
515         goto done;
516      dir_size = dir_info.file_size;
517
518      /* sanity check directory */
519      if (!dir_info.directory)
520      {
521         err = (current_lsn == disk_info->root_dir_lsn) ? IMGTOOLERR_CORRUPTIMAGE : IMGTOOLERR_INVALIDPATH;
522         goto done;
523      }
524
525      /* walk the directory */
526      for (index = 0; index < dir_size; index += 32)
527      {
528         entry_index = index;
529         entry_lsn = os9_lookup_lsn(img, &dir_info, &entry_index);
530         
531         err = os9_read_lsn(img, entry_lsn, entry_index, entry, sizeof(entry));
532         if (err)
533            goto done;
534
535         /* remember first free entry found */
536         if( free_entry_index == 0xffffffff )
537         {
538            if( entry[0] == 0 )
539               free_entry_index = index;
540         }
541
542         if (os9_interpret_dirent(entry, &filename, &current_lsn, NULL))
543         {
544            if (!strcmp(path, filename))
545               break;
546         }
547         
548      }
549
550      /* at the end of the file? */
551      if (index >= dir_size)
552      {
553         /* if we're not creating, or we are creating but we have not fully
554          * transversed the directory, error out */
555         if (!create || path[strlen(path) + 1])
556         {
557            err = IMGTOOLERR_PATHNOTFOUND;
558            goto done;
559         }
560
561         /* allocate a new LSN */
562         err = os9_allocate_lsn(img, &allocated_lsn);
563         if (err)
564            goto done;
565         
566         /* write the file */
567         memset(block, 0, sizeof(block));
568         place_integer_be(block, 0, 1, 0x1B | ((create == CREATE_DIR) ? 0x80 : 0x00));
569         err = os9_write_lsn(img, allocated_lsn, 0, block, sizeof(block));
570         if (err)
571            goto done;
572         
573         if( free_entry_index == 0xffffffff )
574         {
575            /* expand the directory to hold the new entry */
576            err = os9_set_file_size(img, &dir_info, dir_size + 32);
577            if (err)
578               goto done;
579         }
580         else
581            /* use first unused entry in directory */
582            dir_size = free_entry_index;
583
584         /* now prepare the directory entry */
585         memset(entry, 0, sizeof(entry));
586         place_string(entry, 0, 28, path);
587         place_integer_be(entry, 29, 3, allocated_lsn);
588
589         /* now write the directory entry */
590         entry_index = dir_size;
591         entry_lsn = os9_lookup_lsn(img, &dir_info, &entry_index);
592         err = os9_write_lsn(img, entry_lsn, entry_index, entry, 32);
593         if (err)
594            goto done;
595
596         /* directory entry append complete; no need to hold this lsn */
597         current_lsn = allocated_lsn;
598         allocated_lsn = 0;
599      }
600      path += strlen(path) + 1;
601   }
602
603   if (file_info)
604   {
605      err = os9_decode_file_header(img, current_lsn, file_info);
606      if (err)
607         goto done;
608   }
609
610   if (dirent_lsn)
611      *dirent_lsn = entry_lsn;
612   if (dirent_index)
613      *dirent_index = entry_index;
614
615done:
616   if (allocated_lsn != 0)
617      os9_deallocate_lsn(img, allocated_lsn);
618   return err;
619}
620
621
622
623static imgtoolerr_t os9_diskimage_open(imgtool_image *image, imgtool_stream *stream)
624{
625   imgtoolerr_t err;
626   floperr_t ferr;
627   os9_diskinfo *info;
628   UINT32 track_size_in_sectors, attributes, i;
629   UINT8 header[256];
630   UINT32 allocation_bitmap_lsns;
631   UINT8 b, mask;
632
633   info = os9_get_diskinfo(image);
634
635   ferr = floppy_read_sector(imgtool_floppy(image), 0, 0, 1, 0, header, sizeof(header));
636   if (ferr)
637      return imgtool_floppy_error(ferr);
638
639   info->total_sectors            = pick_integer_be(header,   0, 3);
640   track_size_in_sectors         = pick_integer_be(header,   3, 1);
641   info->allocation_bitmap_bytes   = pick_integer_be(header,   4, 2);
642   info->cluster_size            = pick_integer_be(header,   6, 2);
643   info->root_dir_lsn            = pick_integer_be(header,   8, 3);
644   info->owner_id               = pick_integer_be(header,  11, 2);
645   attributes                  = pick_integer_be(header,  13, 1);
646   info->disk_id               = pick_integer_be(header,  14, 2);
647   info->format_flags            = pick_integer_be(header,  16, 1);
648   info->sectors_per_track         = pick_integer_be(header,  17, 2);
649   info->bootstrap_lsn            = pick_integer_be(header,  21, 3);
650   info->bootstrap_size         = pick_integer_be(header,  24, 2);
651   info->sector_size            = pick_integer_be(header, 104, 2);
652
653   info->sides               = (info->format_flags & 0x01) ? 2 : 1;
654   info->double_density      = (info->format_flags & 0x02) ? 1 : 0;
655   info->double_track         = (info->format_flags & 0x04) ? 1 : 0;
656   info->quad_track_density   = (info->format_flags & 0x08) ? 1 : 0;
657   info->octal_track_density   = (info->format_flags & 0x10) ? 1 : 0;
658
659   pick_string(header, 31, 32, info->name);
660
661   if (info->sector_size == 0)
662      info->sector_size = 256;
663
664   /* does the root directory and allocation bitmap collide? */
665   allocation_bitmap_lsns = (info->allocation_bitmap_bytes + info->sector_size - 1) / info->sector_size;
666   if (1 + allocation_bitmap_lsns > info->root_dir_lsn)
667      return IMGTOOLERR_CORRUPTIMAGE;
668
669   /* is the allocation bitmap too big? */
670   info->allocation_bitmap = imgtool_image_malloc(image, info->allocation_bitmap_bytes);
671   if (!info->allocation_bitmap)
672      return IMGTOOLERR_OUTOFMEMORY;
673   memset(info->allocation_bitmap, 0, info->allocation_bitmap_bytes);
674
675   /* sectors per track and track size dont jive? */
676   if (info->sectors_per_track != track_size_in_sectors)
677      return IMGTOOLERR_CORRUPTIMAGE;
678
679   /* zero sectors per track? */
680   if (info->sectors_per_track == 0)
681      return IMGTOOLERR_CORRUPTIMAGE;
682
683   /* do we have an odd number of sectors? */
684   if (info->total_sectors % info->sectors_per_track)
685      return IMGTOOLERR_CORRUPTIMAGE;
686
687   /* read the allocation bitmap */
688   for (i = 0; i < allocation_bitmap_lsns; i++)
689   {
690      err = os9_read_lsn(image, 1 + i, 0, &info->allocation_bitmap[i * info->sector_size],
691         MIN(info->allocation_bitmap_bytes - (i * info->sector_size), info->sector_size));
692      if (err)
693         return err;
694   }
695
696   /* check to make sure that the allocation bitmap and root sector are reserved */
697   for (i = 0; i <= allocation_bitmap_lsns; i++)
698   {
699      b = info->allocation_bitmap[i / 8];
700      mask = 1 << (7 - (i % 8));
701      if ((b & mask) == 0)
702         return IMGTOOLERR_CORRUPTIMAGE;
703   }
704
705   return IMGTOOLERR_SUCCESS;
706}
707
708
709
710static imgtoolerr_t os9_diskimage_create(imgtool_image *img, imgtool_stream *stream, option_resolution *opts)
711{
712   imgtoolerr_t err;
713   UINT8 *header;
714   UINT32 heads, tracks, sectors, sector_bytes, first_sector_id;
715   UINT32 cluster_size, owner_id;
716   UINT32 allocation_bitmap_bits, allocation_bitmap_lsns;
717   UINT32 attributes, format_flags, disk_id;
718   UINT32 i;
719   INT32 total_allocated_sectors;
720   const char *title;
721   time_t t;
722   struct tm *ltime;
723
724   time(&t);
725   ltime = localtime(&t);
726
727   heads = option_resolution_lookup_int(opts, 'H');
728   tracks = option_resolution_lookup_int(opts, 'T');
729   sectors = option_resolution_lookup_int(opts, 'S');
730   sector_bytes = option_resolution_lookup_int(opts, 'L');
731   first_sector_id = option_resolution_lookup_int(opts, 'F');
732   title = "";
733
734   header = malloc(sector_bytes);
735   if (!header)
736   {
737      err = IMGTOOLERR_OUTOFMEMORY;
738      goto done;
739   }
740
741   if (sector_bytes > 256)
742      sector_bytes = 256;
743   cluster_size = 1;
744   owner_id = 1;
745   disk_id = 1;
746   attributes = 0;
747   allocation_bitmap_bits = heads * tracks * sectors / cluster_size;
748   allocation_bitmap_lsns = (allocation_bitmap_bits / 8 + sector_bytes - 1) / sector_bytes;
749   format_flags = ((heads > 1) ? 0x01 : 0x00) | ((tracks > 40) ? 0x02 : 0x00);
750
751   memset(header, 0, sector_bytes);
752   place_integer_be(header,   0,  3, heads * tracks * sectors);
753   place_integer_be(header,   3,  1, sectors);
754   place_integer_be(header,   4,  2, (allocation_bitmap_bits + 7) / 8);
755   place_integer_be(header,   6,  2, cluster_size);
756   place_integer_be(header,   8,  3, 1 + allocation_bitmap_lsns);
757   place_integer_be(header,  11,  2, owner_id);
758   place_integer_be(header,  13,  1, attributes);
759   place_integer_be(header,  14,  2, disk_id);
760   place_integer_be(header,  16,  1, format_flags);
761   place_integer_be(header,  17,  2, sectors);
762   place_string(header,   31, 32, title);
763   place_integer_be(header, 103, 2, sector_bytes / 256);
764   
765   /* path descriptor options */
766   place_integer_be(header, 0x3f+0x00, 1, 1); /* device class */
767   place_integer_be(header, 0x3f+0x01, 1, 1); /* drive number */
768   place_integer_be(header, 0x3f+0x03, 1, 0x20); /* device type */
769   place_integer_be(header, 0x3f+0x04, 1, 1); /* density capability */
770   place_integer_be(header, 0x3f+0x05, 2, tracks); /* number of tracks */
771   place_integer_be(header, 0x3f+0x07, 1, heads); /* number of sides */
772   place_integer_be(header, 0x3f+0x09, 2, sectors); /* sectors per track */
773   place_integer_be(header, 0x3f+0x0b, 2, sectors); /* sectors on track zero */
774   place_integer_be(header, 0x3f+0x0d, 1, 3); /* sector interleave factor */
775   place_integer_be(header, 0x3f+0x0e, 1, 8); /* default sectors per allocation */
776   
777   err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id, 0, header, sector_bytes);
778   if (err)
779      goto done;
780
781   total_allocated_sectors = 1 + allocation_bitmap_lsns + 1 + 7;
782
783   for (i = 0; i < allocation_bitmap_lsns; i++)
784   {
785      memset(header, 0x00, sector_bytes);
786     
787      if (total_allocated_sectors > (8 * 256))
788      {
789         memset(header, 0xff, sector_bytes);
790         total_allocated_sectors -= (8 * 256);
791      }
792      else if (total_allocated_sectors > 1 )
793      {
794         int offset;
795         UINT8 mask;
796           
797         while( total_allocated_sectors >= 0 )
798         {
799            offset = total_allocated_sectors / 8;
800            mask = 1 << (7 - ( total_allocated_sectors % 8 ) );
801
802            header[offset] |= mask;
803            total_allocated_sectors--;
804         }
805      }
806     
807      err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 1 + i, 0, header, sector_bytes);
808      if (err)
809         goto done;
810   }
811
812   memset(header, 0, sector_bytes);
813   header[0x00] = 0xBF;
814   header[0x01] = 0x00;
815   header[0x02] = 0x00;
816   header[0x03] = (UINT8) ltime->tm_year;
817   header[0x04] = (UINT8) ltime->tm_mon + 1;
818   header[0x05] = (UINT8) ltime->tm_mday;
819   header[0x06] = (UINT8) ltime->tm_hour;
820   header[0x07] = (UINT8) ltime->tm_min;
821   header[0x08] = 0x02;
822   header[0x09] = 0x00;
823   header[0x0A] = 0x00;
824   header[0x0B] = 0x00;
825   header[0x0C] = 0x40;
826   header[0x0D] = (UINT8) (ltime->tm_year % 100);
827   header[0x0E] = (UINT8) ltime->tm_mon;
828   header[0x0F] = (UINT8) ltime->tm_mday;
829   place_integer_be(header, 0x10, 3, 1 + allocation_bitmap_lsns + 1);
830   place_integer_be(header, 0x13, 2, 8);
831
832   err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 1 + allocation_bitmap_lsns, 0, header, sector_bytes);
833   if (err)
834      goto done;
835
836   memset(header, 0, sector_bytes);
837   header[0x00] = 0x2E;
838   header[0x01] = 0xAE;
839   header[0x1F] = 1 + allocation_bitmap_lsns;
840   header[0x20] = 0xAE;
841   header[0x3F] = 1 + allocation_bitmap_lsns;
842   err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 2 + allocation_bitmap_lsns, 0, header, sector_bytes);
843   if (err)
844      goto done;
845
846done:
847   if (header)
848      free(header);
849   return err;
850}
851
852
853
854static imgtoolerr_t os9_diskimage_beginenum(imgtool_directory *enumeration, const char *path)
855{
856   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
857   struct os9_direnum *os9enum;
858   imgtool_image *image;
859
860   image = imgtool_directory_image(enumeration);
861   os9enum = os9_get_dirinfo(enumeration);
862
863   err = os9_lookup_path(image, path, CREATE_NONE, &os9enum->dir_info, NULL, NULL, NULL);
864   if (err)
865      goto done;
866
867   /* this had better be a directory */
868   if (!os9enum->dir_info.directory)
869   {
870      err = IMGTOOLERR_CORRUPTIMAGE;
871      goto done;
872   }
873
874done:
875   return err;
876}
877
878
879
880static imgtoolerr_t os9_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
881{
882   struct os9_direnum *os9enum;
883   UINT32 lsn, index;
884   imgtoolerr_t err;
885   UINT8 dir_entry[32];
886   char filename[29];
887   struct os9_fileinfo file_info;
888   imgtool_image *image;
889
890   image = imgtool_directory_image(enumeration);
891   os9enum = os9_get_dirinfo(enumeration);
892
893   do
894   {
895      /* check for EOF */
896      if (os9enum->index >= os9enum->dir_info.file_size)
897      {
898         ent->eof = 1;
899         return IMGTOOLERR_SUCCESS;
900      }
901
902      /* locate the LSN and offset for this directory entry */
903      index = os9enum->index;
904      lsn = os9_lookup_lsn(image, &os9enum->dir_info, &index);
905
906      /* read the directory entry out of the lSN */
907      err = os9_read_lsn(image, lsn, index, dir_entry, sizeof(dir_entry));
908      if (err)
909         return err;
910
911      if (dir_entry[0])
912      {
913         /* read the file or directory name */
914         pick_string(dir_entry, 0, 28, filename);
915
916         /* we have certain expectations of the directory contents; the
917          * first directory entry should be "..", the second ".", and
918          * subsequent entries should never be "." or ".." */
919         switch(os9enum->index)
920         {
921            case 0:
922               if (strcmp(filename, ".."))
923                  imgtool_warn("First entry in directory should be \"..\" and not \"%s\"", filename);
924               break;
925
926            case 32:
927               if (strcmp(filename, "."))
928                  imgtool_warn("Second entry in directory should be \".\" and not \"%s\"", filename);
929               break;
930
931            default:
932               if (!strcmp(filename, ".") || !strcmp(filename, ".."))
933                  imgtool_warn("Directory entry %d should not be \"%s\"", index / 32, filename);
934               break;
935         }
936
937         /* if the filename is ".", the file should point to the current directory */
938         if (!strcmp(filename, ".") && (pick_integer_be(dir_entry, 29, 3) != os9enum->dir_info.lsn))
939         {
940            imgtool_warn("Directory \".\" does not point back to same directory");
941         }
942      }
943      else
944      {
945         /* no more directory entries */
946         filename[0] = '\0';
947      }
948
949      /* move on to the next directory entry */
950      os9enum->index += 32;
951   }
952   while(!filename[0] || !strcmp(filename, ".") || !strcmp(filename, ".."));
953
954   /* read file attributes */
955   lsn = pick_integer_be(dir_entry, 29, 3);
956   err = os9_decode_file_header(imgtool_directory_image(enumeration), lsn, &file_info);
957   if (err)
958      return err;
959
960   /* fill out imgtool_dirent structure */
961   snprintf(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), "%s", filename);
962   snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%c%c%c%c%c%c%c%c",
963      file_info.directory      ? 'd' : '-',
964      file_info.non_sharable   ? 's' : '-',
965      file_info.public_execute ? 'x' : '-',
966      file_info.public_write   ? 'w' : '-',
967      file_info.public_read    ? 'r' : '-',
968      file_info.user_execute   ? 'x' : '-',
969      file_info.user_write     ? 'w' : '-',
970      file_info.user_read      ? 'r' : '-');
971
972   ent->directory = file_info.directory;
973   ent->corrupt = (dir_entry[28] != 0);
974   ent->filesize = file_info.file_size;
975   return IMGTOOLERR_SUCCESS;
976}
977
978
979
980static imgtoolerr_t os9_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
981{
982   imgtool_image *image = imgtool_partition_image(partition);
983   const os9_diskinfo *disk_info;
984   UINT32 free_lsns;
985
986   disk_info = os9_get_diskinfo(image);
987   free_lsns = os9_get_free_lsns(image);
988
989   *size = free_lsns * disk_info->sector_size;
990   return IMGTOOLERR_SUCCESS;
991}
992
993
994
995static imgtoolerr_t os9_diskimage_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
996{
997   imgtoolerr_t err;
998   imgtool_image *img = imgtool_partition_image(partition);
999   const os9_diskinfo *disk_info;
1000   struct os9_fileinfo file_info;
1001   UINT8 buffer[256];
1002   int i, j;
1003   UINT32 file_size;
1004   UINT32 used_size;
1005
1006   disk_info = os9_get_diskinfo(img);
1007
1008   err = os9_lookup_path(img, filename, CREATE_NONE, &file_info, NULL, NULL, NULL);
1009   if (err)
1010      return err;
1011   if (file_info.directory)
1012      return IMGTOOLERR_FILENOTFOUND;
1013   file_size = file_info.file_size;
1014
1015   for (i = 0; file_info.sector_map[i].count > 0; i++)
1016   {
1017      for (j = 0; j < file_info.sector_map[i].count; j++)
1018      {
1019         used_size = MIN(file_size, disk_info->sector_size);
1020         err = os9_read_lsn(img, file_info.sector_map[i].lsn + j, 0,
1021            buffer, used_size);
1022         if (err)
1023            return err;
1024         stream_write(destf, buffer, used_size);
1025         file_size -= used_size;
1026      }
1027   }
1028   return IMGTOOLERR_SUCCESS;
1029}
1030
1031
1032
1033static imgtoolerr_t os9_diskimage_writefile(imgtool_partition *partition, const char *path, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
1034{
1035   imgtoolerr_t err;
1036   imgtool_image *image = imgtool_partition_image(partition);
1037   struct os9_fileinfo file_info;
1038   size_t write_size;
1039   void *buf = NULL;
1040   int i = -1;
1041   UINT32 lsn = 0;
1042   UINT32 count = 0;
1043   UINT32 sz;
1044   const os9_diskinfo *disk_info;
1045
1046   disk_info = os9_get_diskinfo(image);
1047
1048   buf = malloc(disk_info->sector_size);
1049   if (!buf)
1050   {
1051      err = IMGTOOLERR_OUTOFMEMORY;
1052      goto done;
1053   }
1054
1055   err = os9_lookup_path(image, path, CREATE_FILE, &file_info, NULL, NULL, NULL);
1056   if (err)
1057      goto done;
1058
1059   sz = (UINT32) stream_size(sourcef);
1060
1061   err = os9_set_file_size(image, &file_info, sz);
1062   if (err)
1063      goto done;
1064
1065   while(sz > 0)
1066   {
1067      write_size = (size_t) MIN(sz, (UINT64) disk_info->sector_size);
1068
1069      stream_read(sourcef, buf, write_size);
1070
1071      while(count == 0)
1072      {
1073         i++;
1074         lsn = file_info.sector_map[i].lsn;
1075         count = file_info.sector_map[i].count;
1076      }
1077
1078      err = os9_write_lsn(image, lsn, 0, buf, write_size);
1079      if (err)
1080         goto done;
1081
1082      lsn++;
1083      count--;
1084      sz -= write_size;
1085   }
1086
1087done:
1088   if (buf)
1089      free(buf);
1090   return err;
1091}
1092
1093
1094
1095static imgtoolerr_t os9_diskimage_delete(imgtool_partition *partition, const char *path,
1096   unsigned int delete_directory)
1097{
1098   imgtoolerr_t err;
1099   imgtool_image *image = imgtool_partition_image(partition);
1100   const os9_diskinfo *disk_info;
1101   struct os9_fileinfo file_info;
1102   UINT32 dirent_lsn, dirent_index;
1103   UINT32 entry_lsn, entry_index;
1104   UINT32 i, j, lsn;
1105   UINT8 b;
1106
1107   disk_info = os9_get_diskinfo(image);
1108
1109   err = os9_lookup_path(image, path, CREATE_NONE, &file_info, NULL, &dirent_lsn, &dirent_index);
1110   if (err)
1111      return err;
1112   if (file_info.directory != delete_directory)
1113      return IMGTOOLERR_FILENOTFOUND;
1114
1115   /* make sure that if we are deleting a directory, it is empty */
1116   if (delete_directory)
1117   {
1118      for (i = 64; i < file_info.file_size; i += 32)
1119      {
1120         entry_index = i;
1121         entry_lsn = os9_lookup_lsn(image, &file_info, &entry_index);
1122
1123         err = os9_read_lsn(image, entry_lsn, entry_index, &b, 1);
1124         if (err)
1125            return err;
1126
1127         /* this had better be a deleted file, if not we can't delete */
1128         if (b != 0)
1129            return IMGTOOLERR_DIRNOTEMPTY;
1130      }
1131   }
1132
1133   /* zero out the file entry */
1134   b = '\0';
1135   err = os9_write_lsn(image, dirent_lsn, dirent_index, &b, 1);
1136   if (err)
1137      return err;
1138
1139   /* get the link count */
1140   err = os9_read_lsn(image, file_info.lsn, 8, &b, 1);
1141   if (err)
1142      return err;
1143
1144   if (b > 0)
1145      b--;
1146   if (b > 0)
1147   {
1148      /* link count is greater than zero */
1149      err = os9_write_lsn(image, file_info.lsn, 8, &b, 1);
1150      if (err)
1151         return err;
1152   }
1153   else
1154   {
1155      /* no more links; outright delete the file */
1156      err = os9_deallocate_lsn(image, file_info.lsn);
1157      if (err)
1158         return err;
1159
1160      for (i = 0; (i < sizeof(file_info.sector_map) / sizeof(file_info.sector_map[0])) && file_info.sector_map[i].count; i++)
1161      {
1162         lsn = file_info.sector_map[i].lsn;
1163         for (j = 0;  j < file_info.sector_map[i].count; j++)
1164         {
1165            err = os9_deallocate_lsn(image, lsn + j);
1166            if (err)
1167               return err;
1168         }
1169      }
1170   }
1171
1172   return IMGTOOLERR_SUCCESS;
1173}
1174
1175
1176
1177static imgtoolerr_t os9_diskimage_deletefile(imgtool_partition *partition, const char *path)
1178{
1179   return os9_diskimage_delete(partition, path, 0);
1180}
1181
1182
1183
1184static imgtoolerr_t os9_diskimage_createdir(imgtool_partition *partition, const char *path)
1185{
1186   imgtoolerr_t err;
1187   imgtool_image *image = imgtool_partition_image(partition);
1188   struct os9_fileinfo file_info;
1189   UINT8 dir_data[64];
1190   UINT32 parent_lsn;
1191
1192   err = os9_lookup_path(image, path, CREATE_DIR, &file_info, &parent_lsn, NULL, NULL);
1193   if (err)
1194      goto done;
1195
1196   err = os9_set_file_size(image, &file_info, 64);
1197   if (err)
1198      goto done;
1199
1200   /* create intial directories */
1201   memset(dir_data, 0, sizeof(dir_data));
1202   place_string(dir_data,   0, 32, "..");
1203   place_integer_be(dir_data, 29,  3, parent_lsn);
1204   place_string(dir_data,  32, 32, ".");
1205   place_integer_be(dir_data, 61,  3, file_info.lsn);
1206
1207   err = os9_write_lsn(image, file_info.sector_map[0].lsn, 0, dir_data, sizeof(dir_data));
1208   if (err)
1209      goto done;
1210
1211done:
1212   return err;
1213}
1214
1215
1216
1217static imgtoolerr_t os9_diskimage_deletedir(imgtool_partition *partition, const char *path)
1218{
1219   return os9_diskimage_delete(partition, path, 1);
1220}
1221
1222
1223
1224void os9_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
1225{
1226   switch(state)
1227   {
1228      /* --- the following bits of info are returned as 64-bit signed integers --- */
1229      case IMGTOOLINFO_INT_INITIAL_PATH_SEPARATOR:      info->i = 1; break;
1230      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
1231      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(os9_diskinfo); break;
1232      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(struct os9_direnum); break;
1233      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = '/'; break;
1234
1235      /* --- the following bits of info are returned as NULL-terminated strings --- */
1236      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "os9"); break;
1237      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "OS-9 format"); break;
1238      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
1239      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
1240
1241      /* --- the following bits of info are returned as pointers to data or functions --- */
1242      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
1243      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = os9_diskimage_create; break;
1244      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = os9_diskimage_open; break;
1245      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = os9_diskimage_beginenum; break;
1246      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = os9_diskimage_nextenum; break;
1247      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = os9_diskimage_freespace; break;
1248      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = os9_diskimage_readfile; break;
1249      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = os9_diskimage_writefile; break;
1250      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = os9_diskimage_deletefile; break;
1251      case IMGTOOLINFO_PTR_CREATE_DIR:               info->create_dir = os9_diskimage_createdir; break;
1252      case IMGTOOLINFO_PTR_DELETE_DIR:               info->delete_dir = os9_diskimage_deletedir; break;
1253      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_coco; break;
1254   }
1255}
src/mess/tools/imgtool/cybiko.c
r1339r1340
1/*
2
3   Cybiko File System
4
5   (c) 2007 Tim Schuerewegen
6
7*/
8
9#include "imgtool.h"
10
11#include <zlib.h>
12
13#ifndef FALSE
14#    define FALSE 0
15#endif
16#ifndef TRUE
17#    define TRUE (!FALSE)
18#endif
19
20typedef struct _cybiko_file_system cybiko_file_system;
21struct _cybiko_file_system
22{
23   imgtool_stream *stream;
24   UINT32 page_count, page_size, block_count_boot, block_count_file;
25   UINT16 write_count;
26};
27
28typedef struct _cybiko_iter cybiko_iter;
29struct _cybiko_iter
30{
31   UINT16 block;
32};
33
34typedef struct _cfs_file cfs_file;
35struct _cfs_file
36{
37   char name[64]; // name of the file
38   UINT32 date;   // date/time of the file (seconds since 1900/01/01)
39   UINT32 size;   // size of the file
40   UINT32 blocks; // number of blocks occupied by the file
41};
42
43enum
44{
45   BLOCK_TYPE_INVALID,
46   BLOCK_TYPE_BOOT,
47   BLOCK_TYPE_FILE
48};
49
50#define   MAX_PAGE_SIZE (264 * 2)
51
52#define INVALID_FILE_ID  0xFFFF
53
54enum
55{
56   FLASH_TYPE_INVALID,
57   FLASH_TYPE_AT45DB041,
58   FLASH_TYPE_AT45DB081,
59   FLASH_TYPE_AT45DB161
60};
61
62#define BLOCK_USED(x)      (x[0] & 0x80)
63#define BLOCK_FILE_ID(x)   buffer_read_16_be( x + 2)
64#define BLOCK_PART_ID(x)   buffer_read_16_be( x + 4)
65#define BLOCK_FILENAME(x)  (char*)(x + 7)
66
67#define FILE_HEADER_SIZE  0x48
68
69// 2208988800 is the number of seconds between 1900/01/01 and 1970/01/01
70
71static time_t time_crack( UINT32 cfs_time)
72{
73   return (time_t)(cfs_time - 2208988800UL);
74}
75
76static UINT32 time_setup( time_t ansi_time)
77{
78   return (UINT32)(ansi_time + 2208988800UL);
79}
80
81static UINT32 buffer_read_32_be( UINT8 *buffer)
82{
83   return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3] << 0);
84}
85
86static UINT16 buffer_read_16_be( UINT8 *buffer)
87{
88   return (buffer[0] << 8) | (buffer[1] << 0);
89}
90
91static void buffer_write_32_be( UINT8 *buffer, UINT32 data)
92{
93   buffer[0] = (data >> 24) & 0xFF;
94   buffer[1] = (data >> 16) & 0xFF;
95   buffer[2] = (data >>  8) & 0xFF;
96   buffer[3] = (data >>  0) & 0xFF;
97}
98
99static void buffer_write_16_be( UINT8 *buffer, UINT16 data)
100{
101   buffer[0] = (data >> 8) & 0xFF;
102   buffer[1] = (data >> 0) & 0xFF;
103}
104
105// page = crc1 (4) + wcnt (2) + crc2 (2) + data (x) + unk (2)
106
107static UINT32 page_buffer_calc_checksum_1( UINT8 *buffer, UINT32 size, int block_type)
108{
109   return crc32( 0, buffer + 8, (block_type == BLOCK_TYPE_BOOT) ? 250 : size - 10);
110}
111
112static UINT16 page_buffer_calc_checksum_2( UINT8 *buffer)
113{
114   UINT16 val = 0xAF17;
115   val ^= buffer_read_16_be( buffer + 0);
116   val ^= buffer_read_16_be( buffer + 2);
117   val ^= buffer_read_16_be( buffer + 4);
118   return FLIPENDIAN_INT16(val);
119}
120
121static int page_buffer_verify( UINT8 *buffer, UINT32 size, int block_type)
122{
123   UINT32 checksum_page, checksum_calc;
124   // checksum 1
125   checksum_calc = page_buffer_calc_checksum_1( buffer, size, block_type);
126   checksum_page = buffer_read_32_be( buffer + 0);
127   if (checksum_calc != checksum_page) return FALSE;
128   // checksum 2
129   checksum_calc = page_buffer_calc_checksum_2( buffer);
130   checksum_page = buffer_read_16_be( buffer + 6);
131   if (checksum_calc != checksum_page) return FALSE;
132   // ok
133   return TRUE;
134}
135
136static int cfs_block_to_page( cybiko_file_system *cfs, int block_type, UINT32 block, UINT32 *page)
137{
138   switch (block_type)
139   {
140      case BLOCK_TYPE_BOOT : if (page) *page = block; return TRUE;
141      case BLOCK_TYPE_FILE : if (page) *page = block + cfs->block_count_boot; return TRUE;
142      default              : return FALSE;
143   }
144}
145
146static int cfs_page_to_block( cybiko_file_system *cfs, UINT32 page, int *block_type, UINT32 *block)
147{
148   UINT32 tmp = page;
149   // boot block
150   if (tmp < cfs->block_count_boot)
151   {
152      if (block_type) *block_type = BLOCK_TYPE_BOOT;
153      if (block) *block = tmp;
154      return TRUE;
155   }
156   tmp -= cfs->block_count_boot;
157   // file block
158   if (tmp < cfs->block_count_file)
159   {
160      if (block_type) *block_type = BLOCK_TYPE_FILE;
161      if (block) *block = tmp;
162      return TRUE;
163   }
164   tmp -= cfs->block_count_file;
165   // error
166   return FALSE;
167}
168
169static int cfs_page_read( cybiko_file_system *cfs, UINT8 *buffer, UINT32 page)
170{
171   if (page >= cfs->page_count) return FALSE;
172   stream_seek( cfs->stream, page * cfs->page_size, SEEK_SET);
173   stream_read( cfs->stream, buffer, cfs->page_size);
174   return TRUE;
175}
176
177static int cfs_page_write( cybiko_file_system *cfs, UINT8 *buffer, UINT32 page)
178{
179   if (page >= cfs->page_count) return FALSE;
180   stream_seek( cfs->stream, page * cfs->page_size, SEEK_SET);
181   stream_write( cfs->stream, buffer, cfs->page_size);
182   return TRUE;
183}
184
185static int cfs_block_read( cybiko_file_system *cfs, UINT8 *buffer, int block_type, UINT32 block)
186{
187   UINT8 buffer_page[MAX_PAGE_SIZE];
188   UINT32 page;
189   if (!cfs_block_to_page( cfs, block_type, block, &page)) return FALSE;
190   if (!cfs_page_read( cfs, buffer_page, page)) return FALSE;
191   memcpy( buffer, buffer_page + 8, cfs->page_size - 10);
192   return TRUE;
193}
194
195static int cfs_block_write( cybiko_file_system *cfs, UINT8 *buffer, int block_type, UINT32 block)
196{
197   UINT8 buffer_page[MAX_PAGE_SIZE];
198   UINT32 page;
199   memcpy( buffer_page + 8, buffer, cfs->page_size - 10);
200   buffer_write_32_be( buffer_page + 0, page_buffer_calc_checksum_1( buffer_page, cfs->page_size, block_type));
201   buffer_write_16_be( buffer_page + 4, cfs->write_count++);
202   buffer_write_16_be( buffer_page + 6, page_buffer_calc_checksum_2( buffer_page));
203   buffer_write_16_be( buffer_page + cfs->page_size - 2, 0xFFFF);
204   if (!cfs_block_to_page( cfs, block_type, block, &page)) return FALSE;
205   if (!cfs_page_write( cfs, buffer_page, page)) return FALSE;
206   return TRUE;
207}
208
209static int cfs_file_delete( cybiko_file_system *cfs, UINT16 file_id)
210{
211   UINT8 buffer[MAX_PAGE_SIZE];
212   int i;
213   for (i=0;i<cfs->block_count_file;i++)
214   {
215      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
216      if (BLOCK_USED(buffer) && (BLOCK_FILE_ID(buffer) == file_id))
217      {
218         buffer[0] &= ~0x80;
219         if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
220      }
221   }
222   return TRUE;
223}
224
225static int cfs_file_info( cybiko_file_system *cfs, UINT16 file_id, cfs_file *file)
226{
227   UINT8 buffer[MAX_PAGE_SIZE];
228   int i;
229   file->blocks = file->size = 0;
230   for (i=0;i<cfs->block_count_file;i++)
231   {
232      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
233      if (BLOCK_USED(buffer) && (BLOCK_FILE_ID(buffer) == file_id))
234      {
235         if (BLOCK_PART_ID(buffer) == 0)
236         {
237            strcpy( file->name, BLOCK_FILENAME(buffer));
238            file->date = buffer_read_32_be( buffer + 6 + FILE_HEADER_SIZE - 4);
239         }
240         file->size += buffer[1];
241         file->blocks++;
242      }
243   }
244   return (file->blocks > 0) ? TRUE : FALSE;
245}
246
247static int cfs_file_find( cybiko_file_system *cfs, const char *filename, UINT16 *file_id)
248{
249   UINT8 buffer[MAX_PAGE_SIZE];
250   int i;
251   for (i=0;i<cfs->block_count_file;i++)
252   {
253      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
254      if (BLOCK_USED(buffer) && (strncmp( filename, BLOCK_FILENAME(buffer), 40) == 0))
255      {
256         *file_id = i;
257         return TRUE;
258      }
259   }
260   return FALSE;
261}
262
263static int cfs_verify( cybiko_file_system *cfs)
264{
265   UINT8 buffer[MAX_PAGE_SIZE];
266   int i, block_type;
267   for (i=0;i<cfs->page_count;i++)
268   {
269      if (!cfs_page_read( cfs, buffer, i)) return FALSE;
270      if (!cfs_page_to_block( cfs, i, &block_type, NULL)) return FALSE;
271      if (!page_buffer_verify( buffer, cfs->page_size, block_type)) return FALSE;
272   }
273   return TRUE;
274}
275
276static int cfs_init( cybiko_file_system *cfs, imgtool_stream *stream, int flash_type)
277{
278   cfs->stream = stream;
279   switch (flash_type)
280   {
281      case FLASH_TYPE_AT45DB041 : cfs->page_count = 2048; cfs->page_size = 264; break;
282      case FLASH_TYPE_AT45DB081 : cfs->page_count = 4096; cfs->page_size = 264; break;
283      case FLASH_TYPE_AT45DB161 : cfs->page_count = 4096; cfs->page_size = 528; break;
284      default                   : return FALSE;
285   }
286   cfs->block_count_boot = 5;
287   cfs->block_count_file = cfs->page_count - cfs->block_count_boot;
288   cfs->write_count = 0;
289   return TRUE;
290}
291
292static int cfs_format( cybiko_file_system *cfs)
293{
294   UINT8 buffer[MAX_PAGE_SIZE];
295   int i;
296   // boot blocks
297   memset( buffer, 0xFF, sizeof( buffer));
298   for (i=0;i<cfs->block_count_boot;i++)
299   {
300      if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_BOOT, i)) return FALSE;
301   }
302   // file blocks
303   memset( buffer, 0xFF, sizeof( buffer));
304   buffer[0] &= ~0x80;
305   for (i=0;i<cfs->block_count_file;i++)
306   {
307      if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
308   }
309   // ok
310   return TRUE;
311}
312
313static UINT16 cfs_calc_free_blocks( cybiko_file_system *cfs)
314{
315   UINT8 buffer[MAX_PAGE_SIZE];
316   int i;
317   UINT16 blocks = 0;
318   for (i=0;i<cfs->block_count_file;i++)
319   {
320      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return 0;
321      if (!BLOCK_USED(buffer)) blocks++;
322   }
323   return blocks;
324}
325
326static UINT32 cfs_calc_free_space( cybiko_file_system *cfs, UINT16 blocks)
327{
328   UINT32 free_space;
329   free_space = blocks * (cfs->page_size - 0x10);
330   if (free_space > 0) free_space -= FILE_HEADER_SIZE;
331   return free_space;
332}
333
334static int flash_size_to_flash_type( size_t size)
335{
336   switch (size)
337   {
338      case 0x084000 : return FLASH_TYPE_AT45DB041;
339      case 0x108000 : return FLASH_TYPE_AT45DB081;
340      case 0x210000 : return FLASH_TYPE_AT45DB161;
341      default       : return FLASH_TYPE_INVALID;
342   }
343}
344
345static int flash_option_to_flash_type( int option)
346{
347   switch (option)
348   {
349      case 0  : return FLASH_TYPE_AT45DB041;
350      case 1  : return FLASH_TYPE_AT45DB081;
351      case 2  : return FLASH_TYPE_AT45DB161;
352      default : return FLASH_TYPE_INVALID;
353   }
354}
355
356static imgtoolerr_t cybiko_image_open( imgtool_image *image, imgtool_stream *stream)
357{
358   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
359   int flash_type;
360   // init
361   flash_type = flash_size_to_flash_type( stream_size( stream));
362   if (!cfs_init( cfs, stream, flash_type)) return IMGTOOLERR_CORRUPTIMAGE;
363   // verify
364   if (!cfs_verify( cfs)) return IMGTOOLERR_CORRUPTIMAGE;
365   // ok
366   return IMGTOOLERR_SUCCESS;
367}
368
369static void cybiko_image_close( imgtool_image *image)
370{
371   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
372   stream_close( cfs->stream);
373}
374
375static imgtoolerr_t cybiko_image_create( imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
376{
377   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
378   int flash_type;
379   // init
380   flash_type = flash_option_to_flash_type( option_resolution_lookup_int( opts, 'F'));
381   if (!cfs_init( cfs, stream, flash_type)) return IMGTOOLERR_CORRUPTIMAGE;
382   // format
383   if (!cfs_format( cfs)) return IMGTOOLERR_CORRUPTIMAGE;
384   // ok
385   return IMGTOOLERR_SUCCESS;
386}
387
388static imgtoolerr_t cybiko_image_begin_enum( imgtool_directory *enumeration, const char *path)
389{
390   cybiko_iter *iter = (cybiko_iter*)imgtool_directory_extrabytes( enumeration);
391   iter->block = 0;
392   return IMGTOOLERR_SUCCESS;
393}
394
395static imgtoolerr_t cybiko_image_next_enum( imgtool_directory *enumeration, imgtool_dirent *ent)
396{
397   imgtool_image *image = imgtool_directory_image( enumeration);
398   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
399   cybiko_iter *iter = (cybiko_iter*)imgtool_directory_extrabytes( enumeration);
400   UINT8 buffer[MAX_PAGE_SIZE];
401   UINT16 file_id = INVALID_FILE_ID;
402   cfs_file file;
403   // find next file
404   while (iter->block < cfs->block_count_file)
405   {
406      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, iter->block++)) return IMGTOOLERR_READERROR;
407      if (BLOCK_USED(buffer) && (BLOCK_PART_ID(buffer) == 0))
408      {
409         file_id = BLOCK_FILE_ID(buffer);
410         break;
411      }
412   }
413   // get file information
414   if ((file_id != INVALID_FILE_ID) && cfs_file_info( cfs, file_id, &file))
415   {
416      strcpy( ent->filename, file.name);
417      ent->filesize = file.size;
418      ent->lastmodified_time = time_crack( file.date);
419      ent->filesize = file.size;
420   }
421   else
422   {
423      ent->eof = 1;
424   }
425   // ok
426   return IMGTOOLERR_SUCCESS;
427}
428
429static void cybiko_image_close_enum( imgtool_directory *enumeration)
430{
431   // nothing
432}
433
434static imgtoolerr_t cybiko_image_free_space( imgtool_partition *partition, UINT64 *size)
435{
436   imgtool_image *image = imgtool_partition_image( partition);
437   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
438   if (size) *size = cfs_calc_free_space( cfs, cfs_calc_free_blocks( cfs));
439   return IMGTOOLERR_SUCCESS;
440}
441
442static imgtoolerr_t cybiko_image_read_file( imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
443{
444   imgtool_image *image = imgtool_partition_image( partition);
445   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
446   UINT8 buffer[MAX_PAGE_SIZE];
447   UINT16 file_id, part_id = 0, old_part_id;
448   int i;
449   // find file
450   if (!cfs_file_find( cfs, filename, &file_id)) return IMGTOOLERR_FILENOTFOUND;
451   // read file
452   do
453   {
454      old_part_id = part_id;
455      for (i=0;i<cfs->block_count_file;i++)
456      {
457         if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return IMGTOOLERR_READERROR;
458         if (BLOCK_USED(buffer) && (BLOCK_FILE_ID(buffer) == file_id) && (BLOCK_PART_ID(buffer) == part_id))
459         {
460            stream_write( destf, buffer + 6 + ((part_id == 0) ? FILE_HEADER_SIZE : 0), buffer[1]);
461            part_id++;
462         }
463      }
464   } while (old_part_id != part_id);
465   // ok
466   return IMGTOOLERR_SUCCESS;
467}
468
469static imgtoolerr_t cybiko_image_write_file( imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
470{
471   imgtool_image *image = imgtool_partition_image( partition);
472   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
473   UINT8 buffer[MAX_PAGE_SIZE];
474   UINT16 file_id, part_id = 0, free_blocks;
475   UINT64 bytes_left;
476   cfs_file file;
477   int i;
478   // find file
479   if (!cfs_file_find( cfs, filename, &file_id)) file_id = INVALID_FILE_ID;
480   // check free space
481   free_blocks = cfs_calc_free_blocks( cfs);
482   if (file_id != INVALID_FILE_ID)
483   {
484      if (!cfs_file_info( cfs, file_id, &file)) return IMGTOOLERR_UNEXPECTED;
485      free_blocks += file.blocks;
486   }
487   if (cfs_calc_free_space( cfs, free_blocks) < stream_size( sourcef)) return IMGTOOLERR_NOSPACE;
488   // delete file
489   if (file_id != INVALID_FILE_ID)
490   {
491      if (!cfs_file_delete( cfs, file_id)) return IMGTOOLERR_UNEXPECTED;
492   }
493   // create/write destination file
494   bytes_left = stream_size( sourcef);
495   i = 0;
496   while ((bytes_left > 0) && (i < cfs->block_count_file))
497   {
498      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return IMGTOOLERR_READERROR;
499      if (!BLOCK_USED(buffer))
500      {
501         if (part_id == 0) file_id = i;
502         memset( buffer, 0xFF, cfs->page_size - 0x10);
503         buffer[0] = 0x80;
504         buffer[1] = cfs->page_size - 0x10 - ((part_id == 0) ? FILE_HEADER_SIZE : 0);
505         if (bytes_left < buffer[1]) buffer[1] = bytes_left;
506         buffer_write_16_be( buffer + 2, file_id);
507         buffer_write_16_be( buffer + 4, part_id);
508         if (part_id == 0)
509         {
510            buffer[6] = 0;
511            strcpy( BLOCK_FILENAME(buffer), filename);
512            buffer_write_32_be( buffer + 6 + FILE_HEADER_SIZE - 4, time_setup( time( NULL)));
513            stream_read( sourcef, buffer + 6 + FILE_HEADER_SIZE, buffer[1]);
514         }
515         else
516         {
517            stream_read( sourcef, buffer + 6, buffer[1]);
518         }
519         if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_FILE, i)) return IMGTOOLERR_WRITEERROR;
520         bytes_left -= buffer[1];
521         part_id++;
522      }
523      i++;
524   }
525   // ok
526   return IMGTOOLERR_SUCCESS;
527}
528
529static imgtoolerr_t cybiko_image_delete_file( imgtool_partition *partition, const char *filename)
530{
531   imgtool_image *image = imgtool_partition_image( partition);
532   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
533   UINT16 file_id;
534   // find file
535   if (!cfs_file_find( cfs, filename, &file_id)) return IMGTOOLERR_FILENOTFOUND;
536   // delete file
537   if (!cfs_file_delete( cfs, file_id)) return IMGTOOLERR_UNEXPECTED;
538   // ok
539   return IMGTOOLERR_SUCCESS;
540}
541
542OPTION_GUIDE_START( cybiko_image_createimage_optguide )
543   OPTION_ENUM_START( 'F', "flash", "Flash Type" )
544      OPTION_ENUM( 0, "AT45DB041", "AT45DB041 (528 KByte)" )
545      OPTION_ENUM( 1, "AT45DB081", "AT45DB081 (1056 KByte)" )
546      OPTION_ENUM( 2, "AT45DB161", "AT45DB161 (2112 KByte)" )
547   OPTION_ENUM_END
548OPTION_GUIDE_END
549
550//OPTION_GUIDE_START( cybiko_image_writefile_optguide )
551//   OPTION_INT( 'B', "boot", "Boot Flag" )
552//OPTION_GUIDE_END
553
554void cybiko_get_info( const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
555{
556   switch (state)
557   {
558      // --- the following bits of info are returned as 64-bit signed integers ---
559      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES          : info->i = sizeof( cybiko_file_system); break;
560      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES      : info->i = sizeof( cybiko_iter); break;
561//      case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME     : info->i = 1; break;
562      case IMGTOOLINFO_INT_SUPPORTS_LASTMODIFIED_TIME : info->i = 1; break;
563//      case IMGTOOLINFO_INT_BLOCK_SIZE                 : info->i = 264; break;
564      // --- the following bits of info are returned as pointers to data or functions ---
565      case IMGTOOLINFO_PTR_OPEN        : info->open        = cybiko_image_open; break;
566      case IMGTOOLINFO_PTR_CREATE      : info->create      = cybiko_image_create; break;
567      case IMGTOOLINFO_PTR_CLOSE       : info->close       = cybiko_image_close; break;
568      case IMGTOOLINFO_PTR_BEGIN_ENUM  : info->begin_enum  = cybiko_image_begin_enum; break;
569      case IMGTOOLINFO_PTR_NEXT_ENUM   : info->next_enum   = cybiko_image_next_enum; break;
570      case IMGTOOLINFO_PTR_CLOSE_ENUM  : info->close_enum  = cybiko_image_close_enum; break;
571      case IMGTOOLINFO_PTR_FREE_SPACE  : info->free_space  = cybiko_image_free_space; break;
572      case IMGTOOLINFO_PTR_READ_FILE   : info->read_file   = cybiko_image_read_file; break;
573      case IMGTOOLINFO_PTR_WRITE_FILE  : info->write_file  = cybiko_image_write_file; break;
574      case IMGTOOLINFO_PTR_DELETE_FILE : info->delete_file = cybiko_image_delete_file; break;
575      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE : info->createimage_optguide = cybiko_image_createimage_optguide; break;
576//      case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE   : info->writefile_optguide   = cybiko_image_writefile_optguide; break;
577      // --- the following bits of info are returned as NULL-terminated strings ---
578      case IMGTOOLINFO_STR_NAME            : strcpy( info->s = imgtool_temp_str(), "cybiko"); break;
579      case IMGTOOLINFO_STR_DESCRIPTION     : strcpy( info->s = imgtool_temp_str(), "Cybiko File System"); break;
580      case IMGTOOLINFO_STR_FILE            : strcpy( info->s = imgtool_temp_str(), __FILE__); break;
581      case IMGTOOLINFO_STR_FILE_EXTENSIONS : strcpy( info->s = imgtool_temp_str(), "bin,nv"); break;
582      case IMGTOOLINFO_STR_EOLN            : strcpy( info->s = imgtool_temp_str(), "\r\n"); break;
583      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC : strcpy( info->s = imgtool_temp_str(), "F[0]-2"); break;
584//      case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC   : strcpy( info->s = imgtool_temp_str(), "B[0]-1"); break;
585   }
586}
src/mess/tools/imgtool/thomson.c
r1339r1340
1/****************************************************************************
2
3  Copyright (C) Antoine Mine' 2006
4
5  Thomson 8-bit micro-computers.
6
7  Handles SAP, QD and FD floppy formats with a BASIC-DOS filesystem
8  (most floppies except some games and demo).
9
10*****************************************************************************/
11
12/* TODO:
13   - improve two-sided floppy support
14   - check & correct BASIC read filter
15   - implement BASIC write filter
16   - handle accented letters
17 */
18
19
20/* Thomson floppy geometry are:
21   - 5"1/4 single density: 40 tracks, 16 sectors/track, 128 bytes/sector
22   - 5"1/4 double density: 40 tracks, 16 sectors/track, 256 bytes/sector
23   - 3"1/2 double density: 80 tracks, 16 sectors/track, 256 bytes/sector
24   - 2"8: 25 logical tracks, 16 logical sectors/track, 128 bytes/sector
25
26   Notes:
27
28   - 2"8 QDD actually contain a single spiraling track, with 400 128-byte
29   sectors; however, the filesystem considers it has 25 virtual tracks of
30   16 sectors => we do the same in imgtool (but thomflop.c uses a 400-sector
31   addressing to emulate the device hardware)
32
33   - tracks always have 16 sectors, this is requred by the filesystem
34
35   - two-sided floppies are handled as two one-sided floppies in two
36   logical floppy drives on the original Thomsons; each has its own
37   independent FAT and directory.
38   In imgtool, we handle two-sided images as two partitions.
39   For now, only 3"1/2 .fd and QDD .qd files can be two-sided.
40
41   - it seems possible to create 3"1/2 single density floppies on the TO9,
42   I am not sure this is standard, and we do not support it...
43
44*/
45
46
47/* Microsoft BASIC Filesystem.
48
49   The floppy is divided into blocks, with always two blocks / track.
50   Also, in double density, only the first 255 bytes of each 256-byte
51   sector is used. Thus, blocks are 1024 bytes in single density, and
52   2040 bytes in double density.
53   Depending on the number of tracks, there can be 50, 80 or 160 blocks.
54
55   Filesystem data always occupy track 20, whatever the floppy geometry.
56   
57   * sector 1:
58     - bytes 0-7: floppy name
59     - remaining bytes: undocumented, seem unused
60
61   * sector 2: FAT, 1 byte info per block
62     - byte 0: always 0
63     - byte 1: block 0
64        ...
65     - byte i: block i-1
66        ...
67     - byte 160: block 159
68     - remaining bytes: undocumented, seem unused
69
70     The byte has the following meaning:
71     - ff: block is free
72     - fb: block is reserved
73     - 00-bf: block allocated, points to then next file block
74     - c1-c8: last block in file, (value & 15) is the number of sectors
75              actually allocated to the file
76
77     Note: in single density, we can reference only 127 blocks. This is not
78     a problem because single density floppies can only have 50 or 80 blocks,
79     never 160.
80     
81   * sector 3-16: directory
82
83     no subdirectories
84
85     each file entry occupies 32 bytes:
86     - bytes 00-07: filename, padded with whitespaces
87     - bytes 08-0A: file extension, padedd with whitespaces
88     - byte  0B:    file type
89                    . 0 = BASIC, ASCII or binary program (B)
90             . 1 = BASIC or ASCII data (D)
91          . 2 = machine code (M)
92          . 3 = ASCII assembler file (A)
93     - byte  0C:    format flag
94           . 00 = binary (tokenized)
95                    . ff = ASCII
96     - byte  0D:    first block
97     - bytes 0E-0F: bytes used in the last sector
98     - bytes 10-17: comment
99     - byte 18:     day (of month)
100     - byte 19:     month
101     - byte 1A:     year (two last digits)
102     - bytes 1B-1f: unknown
103
104     Note that byte 0 has a special significance:
105     - 00:    free directory entry
106     - 20-7F: actual directory entry, value is the first character ini filename
107     - ff:    end of directory
108
109     There can be 56 files in single density, 112 in double density.
110 */
111
112#include "imgtool.h"
113#include "iflopimg.h"
114#include "formats/basicdsk.h"
115
116#include <time.h>
117
118
119#define MAXSIZE 80*16*256*2 /* room for two faces, double-density, 80 tracks */
120
121typedef struct {
122
123  imgtool_stream *stream;
124
125  UINT16 sector_size;   /* 128 or 256 */
126  UINT16 sectuse_size;  /* bytes used in sector: 128 or 255 */
127  UINT8  tracks;        /* 25, 40, or 80 */
128  UINT8  heads;         /* 1 or 2 */
129  UINT8  data[MAXSIZE]; /* image data */
130
131  int    modified;      /* data need to be copied back to image file */
132
133} thom_floppy;
134
135
136typedef enum {
137
138  THOM_DIRENT_END,
139  THOM_DIRENT_FREE,
140  THOM_DIRENT_FILE,
141  THOM_DIRENT_INVALID,
142
143} thom_dirent_type;
144
145
146typedef struct {
147
148  thom_dirent_type type;
149  int    index;
150
151  char   name[9];
152  char   ext[4];
153  char   comment[9];
154  UINT8  ftype;
155  UINT8  format;
156  UINT8  firstblock;
157  UINT16 lastsectsize;
158  UINT8  day;
159  UINT8  month;
160  UINT8  year;
161
162} thom_dirent;
163
164
165static void thom_basic_get_info(const imgtool_class *clas, UINT32 param,
166            union imgtoolinfo *info);
167
168static UINT8* thom_get_sector(thom_floppy* f, unsigned head,
169               unsigned track, unsigned sector);
170
171
172/*********************** .fd / .qd format ************************/
173
174/* .fd and .qd formats are very simple: the sectors are simply put one after
175   another, starting at sector 1 of track 0 to sector 16 track 0, then
176   starting again at sector 1 of track 1, and so on.
177   There is no image or sector header, and no gap between sectors.
178   The number of tracks and sector size are determined by the extension
179   (.fd have 40 or 80 tracks, .qd have 25 tracks) and the file size.
180*/
181
182static imgtoolerr_t thom_open_fd_qd(imgtool_image *img, imgtool_stream *stream)
183{
184  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
185  int size = stream_size( stream );
186 
187  f->stream = stream;
188  f->modified = 0;
189
190  /* guess format */
191  switch ( size ) {
192
193  case 81920:
194    f->tracks = 40;
195    f->sector_size = 128;
196    f->sectuse_size = 128;
197    f->heads = 1;
198    break;
199
200  case 163840:
201    f->tracks = 40;
202    f->sector_size = 256;
203    f->sectuse_size = 255;
204    f->heads = 1;
205    /* could also be: sector_size=128, heads=2 */
206    /* maight even be: tracks=80, sector_size=128 */
207    break;
208
209  case 327680:
210    f->tracks = 80;
211    f->sector_size = 256;
212    f->sectuse_size = 255;
213    f->heads = 1;
214    /* could also be: tracks=40, heads=2 */
215    break;
216
217  case 655360:
218    f->tracks = 80;
219    f->sector_size = 256;
220    f->sectuse_size = 255;
221    f->heads = 2;
222    break;
223
224  case 51200:
225    f->tracks = 25;
226    f->sector_size = 128;
227    f->sectuse_size = 128;
228    f->heads = 1;
229    break;
230
231  case 62400:
232    f->tracks = 25;
233    f->sector_size = 128;
234    f->sectuse_size = 128;
235    f->heads = 2;
236    break;
237
238  default:
239    return IMGTOOLERR_CORRUPTIMAGE;
240  }
241 
242  assert( size == f->heads * f->tracks * 16 * f->sector_size );
243
244  stream_seek( stream, 0, SEEK_SET );
245  if ( stream_read( stream, f->data, size ) < size )
246    return IMGTOOLERR_READERROR;
247
248  return IMGTOOLERR_SUCCESS;
249}
250
251static void thom_close_fd_qd(imgtool_image *img)
252{
253  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
254
255  /* save image */
256  if ( f->modified ) {
257    int size = f->heads * f->tracks * 16 * f->sector_size;
258    stream_seek( f->stream, 0, SEEK_SET );
259    if ( stream_write( f->stream, f->data, size ) < size )
260      logerror( "thom_diskimage_close_fd_qd: write error\n" );
261  }
262
263  stream_close( f->stream );
264}
265
266
267/*********************** .sap format ************************/
268
269/* SAP format, Copyright 1998 by Alexandre Pukall
270
271   image is composed of:
272   - byte 0:        version (0 or 1)
273   - bytes 1..65:   signature
274   - bytes 66..end: sectors
275 
276   each sector is composed of
277   - a 4-byte header:
278     . byte 0:     format
279                      0 3"1/2 double density
280                      1 5"1/4 low density
281     . byte 1:     protection (?)
282     . byte 2:     track index, in 0..79
283     . byte 3:     sector index, in 1..16
284   - sector data, XOR 0xB3
285   - 2-byte CRC of header + data, high byte first
286
287   there is no provision for two-sided images in sap
288 */
289
290static const int sap_magic_num = 0xB3; /* simple XOR crypt */
291
292static const char sap_header[]=
293  "\001SYSTEME D'ARCHIVAGE PUKALL S.A.P. "
294  "(c) Alexandre PUKALL Avril 1998";
295
296static const UINT16 sap_crc[] = {
297  0x0000, 0x1081, 0x2102, 0x3183,   0x4204, 0x5285, 0x6306, 0x7387,
298  0x8408, 0x9489, 0xa50a, 0xb58b,   0xc60c, 0xd68d, 0xe70e, 0xf78f,
299};
300
301static UINT16 thom_sap_crc( UINT8* data, int size )
302{
303  int i;
304  UINT16 crc = 0xffff, crc2;
305  for ( i = 0; i < size; i++ ) {
306    crc2 = ( crc >> 4 ) ^ sap_crc[ ( crc ^ data[i] ) & 15 ];
307    crc = ( crc2 >> 4 ) ^ sap_crc[ ( crc2 ^ (data[i] >> 4) ) & 15 ];
308  }
309  return crc;
310}
311
312static imgtoolerr_t thom_open_sap(imgtool_image *img, imgtool_stream *stream)
313{
314  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
315  UINT8 buf[262];
316 
317  f->stream = stream;
318  f->modified = 0;
319
320 /* check image header */
321  stream_seek( stream, 0, SEEK_SET );
322  stream_read( stream, buf, 66 );
323  if ( memcmp( buf+1, sap_header+1, 65 ) ) return IMGTOOLERR_CORRUPTIMAGE;
324
325  /* guess format */
326  stream_read( stream, buf, 1 );
327  switch ( buf[0] ) {
328  case 1:
329  case 3:
330    f->heads = 1;
331    f->tracks = 40;
332    f->sector_size = 128;
333    f->sectuse_size = 128;
334    break;
335  case 0:
336  case 2:
337  case 4:
338    f->heads = 1;
339    f->tracks = 80;
340    f->sector_size = 256;
341    f->sectuse_size = 255;
342    break;
343  default: return IMGTOOLERR_CORRUPTIMAGE;
344  }
345 
346 stream_seek( stream, 66, SEEK_SET );
347  while ( 1) {
348    int i, sector, track;
349    UINT16 crc;
350
351    /* load sector */
352    if ( stream_read( stream, buf, 6 + f->sector_size ) < 6 + f->sector_size )
353      break;
354
355    /* parse sector header */
356    track = buf[2];
357    sector = buf[3];
358    if ( sector < 1 || sector > 16 || track >= f->tracks )
359      return IMGTOOLERR_CORRUPTIMAGE;
360
361    /* decrypt */
362    for ( i = 0; i < f->sector_size; i++ ) buf[ i + 4 ] ^= sap_magic_num;
363    memcpy( thom_get_sector( f, 0, track, sector ), buf + 4, f->sector_size );
364
365    /* check CRC */
366    crc = thom_sap_crc( buf, f->sector_size + 4 );
367    if ( ( (crc >> 8)   != buf[ f->sector_size + 4 ] ) ||
368         ( (crc & 0xff) != buf[ f->sector_size + 5 ] ) )
369      return IMGTOOLERR_CORRUPTIMAGE;
370  }
371
372  return IMGTOOLERR_SUCCESS;
373}
374
375static void thom_close_sap(imgtool_image *img)
376{
377  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
378
379  if ( f->modified ) {
380    int i, sector, track;
381    UINT8 buf[262];
382    UINT16 crc;
383
384    /* rewind */
385    stream_seek( f->stream, 0, SEEK_SET );
386
387    /* image header */
388    if ( stream_write( f->stream, sap_header, 66 ) < 66 ) {
389      logerror( "thom_diskimage_close_sap: write error\n" );
390      return;
391    }
392   
393    for ( track = 0; track < f->tracks; track++ )
394      for ( sector = 1; sector <= 16; sector++ ) {
395
396   /* sector header & data */
397   buf[0] = ( f->tracks == 80 ) ? 2 : 1;
398   buf[1] = 0;
399   buf[2] = track;
400   buf[3] = sector;
401   memcpy( buf + 4,
402      thom_get_sector( f, 0, track, sector), f->sector_size );
403
404   /* compute crc */
405   crc = thom_sap_crc( buf, f->sector_size + 4 );
406   buf[ f->sector_size + 4 ] = crc >> 8;
407   buf[ f->sector_size + 5 ] = crc & 0xff;
408
409   /* crypt */
410   for ( i = 0; i < f->sector_size; i++ ) buf[ i + 4 ] ^= sap_magic_num;
411
412   /* save */
413   if ( stream_write( f->stream, buf, f->sector_size + 6 ) <
414        f->sector_size + 6 ) {
415     logerror( "thom_diskimage_close_sap: write error\n" );
416     return;
417   }
418      }
419  }
420 
421  stream_close( f->stream );
422}
423
424
425/*********************** low-level functions *********************/
426
427static UINT8* thom_get_sector(thom_floppy* f, unsigned head,
428               unsigned track, unsigned sector)
429{
430  assert( head < f->heads);
431  assert( track < f->tracks );
432  assert( sector > 0 && sector <= 16 );
433  return & f->data[ ( (head * f->tracks + track) * 16 + (sector-1) ) *
434          f->sector_size ];
435}
436
437static int thom_nb_blocks(thom_floppy* f)
438{
439  int n1 = f->tracks * 2;      /* 2 blocks per track */
440  int n2 = f->sector_size - 1; /* FAT entries */
441  return (n1 < n2) ? n1 : n2;
442}
443
444static int thom_max_dirent(thom_floppy* f)
445{
446  return 14 * f->sector_size / 32;
447}
448
449/* remove trailing spaces */
450static void thom_stringify(char* str)
451{
452  char* s = str + strlen(str) - 1;
453  while ( s >= str && *s == ' ' ) { *s = 0; s--; }
454  for ( s = str; *s; s++ )
455    if ( (UINT8)*s == 0xff ) *s = 0;
456    else if ( *s < ' ' || *s >= 127 ) *s = '?';
457}
458
459/* pad with spaces until the length is nb */
460static void thom_unstringity(char* str, int nb)
461{
462  char* s = str;
463  while ( s < str + nb && *s ) s++;
464  while ( s < str + nb ) { *s = ' '; s++; }
465}
466
467/* get filename and extension & truncate them to 8 + 3 */
468static void thom_conv_filename(const char* s, char name[9], char ext[4])
469{
470  int i;
471  memset( name, 0, 9 );
472  memset( ext, 0, 4 );
473  for ( i = 0; i < 8 && *s && *s != '.'; i++, s++ ) name[i] = *s;
474  while ( *s && *s != '.' ) s++;
475  if ( *s == '.' ) {
476    s++;
477    for ( i = 0; i < 3 && *s; i++, s++ ) ext[i] = *s;
478  }
479}
480
481static time_t thom_crack_time(thom_dirent* d)
482{
483  struct tm t;
484  time_t now;
485
486  /* check */
487  if ( d->day < 1 || d->day > 31 || d->month < 1 || d->month > 12 ) return 0;
488
489  /* converts */
490  time( &now );
491  t = *localtime( &now );
492  t.tm_sec = 0;
493  t.tm_min = 0;
494  t.tm_hour = 0;
495  t.tm_mday = d->day;
496  t.tm_mon = d->month - 1;
497  t.tm_year = (d->year < 65 ) ? d->year + 100 : d->year;
498  return mktime(&t);
499}
500
501static void thom_make_time(thom_dirent* d, time_t time)
502{
503  if ( ! time ) {
504    d->day = d->month = d->year = 0;
505  }
506  else {
507    struct tm t = *localtime( &time );
508    d->day = t.tm_mday;
509    d->month = t.tm_mon + 1;
510    d->year = t.tm_year % 100;
511  }
512}
513
514static void thom_make_time_now(thom_dirent* d)
515{
516  time_t now;
517  time( &now );
518  thom_make_time( d, now );
519}
520
521static void thom_get_dirent(thom_floppy* f, unsigned head,
522             unsigned n, thom_dirent* d)
523{
524  UINT8* base = thom_get_sector( f, head, 20, 3 ) + n * 32;
525  memset( d, 0, sizeof(*d) );
526  d->index = n;
527  if ( n >= thom_max_dirent( f ) )
528    d->type = THOM_DIRENT_END;
529  else if ( *base == 0xff )
530    d->type = THOM_DIRENT_END;
531  else if ( *base == 0 )
532    d->type = THOM_DIRENT_FREE;
533  else {
534    int i;
535    /* fill regular entry */
536    d->type = THOM_DIRENT_FILE;
537    memcpy( d->name, base, 8 );
538    memcpy( d->ext, base + 8, 3 );
539    memcpy( d->comment, base + 16, 8 );
540    thom_stringify( d->name );
541    thom_stringify( d->ext );
542    thom_stringify( d->comment );
543    d->ftype = base[11];
544    d->format = base[12];
545    d->firstblock = base[13];
546    d->lastsectsize = ((int)base[14] << 8) + base[15];
547    d->day = base[24];
548    d->month = base[25];
549    d->year = base[26];
550    /* sanity check */
551    for ( i = 0; i < 11; i++ )
552      if ( base[i] < ' ' || base[i] > 127 ) d->type = THOM_DIRENT_INVALID;
553  }
554}
555
556static void thom_set_dirent(thom_floppy* f, unsigned head,
557             unsigned n, thom_dirent* d)
558{
559  UINT8* base = thom_get_sector( f, head, 20, 3 ) + n * 32;
560  if ( n >= thom_max_dirent( f ) ) return;
561  memset( base, 0, 32 );
562  if ( d->type == THOM_DIRENT_END ) base[ 0 ] = 0xff;
563  else if ( d->type == THOM_DIRENT_FREE ) base[ 0 ] = 0;
564  else {
565    memcpy( base, d->name, 8 );
566    memcpy( base + 8, d->ext, 3 );
567    memcpy( base + 16, d->comment, 8 );
568    thom_unstringity( (char*)base, 8 );
569    thom_unstringity( (char*)base + 8, 3 );
570    if ( base[16] ) thom_unstringity( (char*)base + 16, 8 );
571    base[11] = d->ftype;
572    base[12] = d->format;
573    base[13] = d->firstblock;
574    base[14] = d->lastsectsize >> 8;
575    base[15] = d->lastsectsize & 0xff;
576    base[24] = d->day;
577    base[25] = d->month;
578    base[26] = d->year;
579  }
580  f->modified = 1;
581}
582
583/* returns 1 if file found, 0 if not */
584static int thom_find_dirent(thom_floppy* f, unsigned head,
585             const char* name, thom_dirent* d)
586{
587  int n = 0;
588  while ( 1 ) {
589    thom_get_dirent( f, head, n, d );
590    if ( d->type == THOM_DIRENT_END ) return 0;
591    if ( d->type == THOM_DIRENT_FILE ) {
592      char buf[13];
593      sprintf( buf, "%s.%s", d->name, d->ext );
594      if ( ! strcmp( buf, name ) ) return 1;
595    }
596    n++;
597  }
598}
599
600/* returns 1 if free entry found, 0 if none available */
601static int thom_find_free_dirent(thom_floppy* f, unsigned head, thom_dirent* d)
602{
603  int n = 0;
604  while ( 1 ) {
605    thom_get_dirent( f, head, n, d );
606    if ( d->type == THOM_DIRENT_FREE ) return 1;
607    if ( d->type == THOM_DIRENT_END ) break;
608    n++;
609  }
610  if ( n + 1 >= thom_max_dirent( f ) ) return 0;
611  thom_set_dirent( f, head, n+1, d );
612  d->type = THOM_DIRENT_FREE;
613  return 1;
614}
615
616/* returns the file size in bytes, or -1 if error */
617static int thom_get_file_size(thom_floppy* f, unsigned head, thom_dirent* d)
618{
619  UINT8* fat = thom_get_sector( f, head, 20, 2 );
620  int nbblocks = thom_nb_blocks(f);
621  int block = d->firstblock;
622  int size = 0;
623  int timeout = nbblocks;
624  if ( d->type != THOM_DIRENT_FILE ) return -1;
625  if ( block >= nbblocks ) return -1;
626  block = fat[ block + 1 ];
627  while ( 1 ) {
628    if ( block < nbblocks ) {
629      /* full block */
630      size += 8 * f->sectuse_size;
631      block = fat[ block + 1 ];
632    }
633    else if ( block >= 0xc1 && block <= 0xc8 ) {
634      /* last block in file */
635      size += (block-0xc1) * f->sectuse_size;
636      size += d->lastsectsize;
637      return size;
638    }
639    else return -1;
640    timeout--;
641    if ( timeout < 0 ) return -1;
642   }
643}
644
645/* number of blocks used by file */
646static int thom_get_file_blocks(thom_floppy* f, unsigned head, thom_dirent* d)
647{
648  UINT8* fat = thom_get_sector( f, head, 20, 2 );
649  int nbblocks = thom_nb_blocks(f);
650  int block = d->firstblock;
651  int nb = 0;
652  if ( d->type != THOM_DIRENT_FILE ) return 0;
653  if ( block >= nbblocks ) return 0;
654  block = fat[ block + 1 ];
655  while ( 1 ) {
656    if ( block < nbblocks ) {
657      /* full block */
658      nb++;
659      block = fat[ block + 1 ];
660    }
661    else if ( block >= 0xc1 && block <= 0xc8 ) {
662      /* last block in file */
663      nb++;
664      return nb;
665    }
666    else return nb;
667  }
668}
669
670/* number of free blocks */
671static int thom_get_free_blocks(thom_floppy* f, unsigned head)
672{
673  UINT8* fat = thom_get_sector( f, head, 20, 2 );
674  int nbblocks = thom_nb_blocks(f);
675  int i, nb = 0;
676  for ( i = 1; i <= nbblocks; i++ )
677    if ( fat[i] == 0xff ) nb++;
678  return nb;
679}
680
681/* dump file contents into dst */
682static void thom_get_file(thom_floppy* f, unsigned head,
683           thom_dirent* d, imgtool_stream *dst)
684{
685  UINT8* fat = thom_get_sector( f, head, 20, 2 );
686  int nbblocks = thom_nb_blocks(f);
687  int block = d->firstblock;
688  if ( block >= nbblocks ) return;
689  while ( 1 ) {
690    int nextblock = fat[ block + 1 ];
691    int track = block / 2;
692    int firstsect = (block % 2) ? 9 : 1;
693    if ( nextblock < nbblocks ) {
694      /* full block */
695      int i;
696      for ( i = 0; i < 8; i++ ) {
697   UINT8* data = thom_get_sector( f, head, track, firstsect + i );
698   stream_write( dst, data, f->sectuse_size );
699      }
700      block = fat[ block + 1 ];
701    }
702    else if ( nextblock >= 0xc1 && nextblock <= 0xc8 ) {
703      /* last block in file */
704      int i;
705      UINT8* data;
706      for ( i = 0; i < nextblock - 0xc1; i++ ) {
707   data = thom_get_sector( f, head, track, firstsect + i );
708   stream_write( dst, data, f->sectuse_size );
709      }
710      data = thom_get_sector( f, head, track, firstsect + i );
711      stream_write( dst, data, d->lastsectsize );
712      return;
713    }
714    else {
715      /* invalid, assume last block */
716      UINT8* data = thom_get_sector( f, head, track, firstsect );
717      stream_write( dst, data, d->lastsectsize );
718      return;
719    }
720    block = nextblock;
721  }
722}
723
724static void thom_del_file(thom_floppy* f, unsigned head, thom_dirent* d)
725{
726  UINT8* fat = thom_get_sector( f, head, 20, 2 );
727  int nbblocks = thom_nb_blocks(f);
728  int block = d->firstblock;
729  if ( d->type != THOM_DIRENT_FILE ) return;
730  if ( block >= nbblocks ) return;
731  while ( 1 ) {
732    int nextblock = fat[ block + 1 ];
733    fat[ block ] = 0xff;
734    if ( nextblock < nbblocks ) block = fat[ block + 1 ];
735    else break;
736  }
737  d->type = THOM_DIRENT_FREE;
738  thom_set_dirent( f, head, d->index, d );
739  f->modified = 1;
740}
741
742/* create a new file or overwrite an old one, with the contents of src */
743static void thom_put_file(thom_floppy* f, unsigned head,
744           thom_dirent* d, imgtool_stream *src)
745{
746  int size = stream_size( src );
747  UINT8* fat = thom_get_sector( f, head, 20, 2 );
748  int nbblocks = thom_nb_blocks(f);
749  int block;
750
751  /* find first free block */
752  for ( block = 0; block < nbblocks && fat[ block + 1 ] != 0xff; block++ );
753  if ( block >= nbblocks ) return;
754  d->firstblock = block;
755
756  /* store file */
757  while (1) {
758    int track = block / 2;
759    int firstsect = (block % 2) ? 9 : 1;
760    int i;
761
762    /* store data, full sectors */
763    for ( i = 0; i < 8 && size > f->sectuse_size; i++ ) {
764      UINT8* dst = thom_get_sector( f, head, track, firstsect + i );
765      stream_read( src, dst, f->sectuse_size );
766      size -= f->sectuse_size;
767    }
768
769    /* store data, last sector */
770    if ( i < 8 ) {
771      UINT8* dst = thom_get_sector( f, head, track, firstsect + i );
772      stream_read( src, dst, size );
773      fat[ block + 1 ] = 0xc1 + i;
774      d->lastsectsize = size;
775      break;
776    }
777   
778    /* find next free block & update fat */
779    i = block;
780    for ( block++; block < nbblocks && fat[ block + 1 ] != 0xff; block++ );
781    if ( block >= nbblocks ) {
782      /* out of memory! */
783      fat[ i + 1 ] = 0;
784      d->lastsectsize = 0;
785      break;
786    }
787    fat[ i + 1 ] = block;
788  }
789
790  d->type = THOM_DIRENT_FILE;
791  thom_set_dirent( f, head, d->index, d );
792  f->modified = 1;
793}
794
795
796/********************** module functions ***********************/
797
798static imgtoolerr_t thom_get_sector_size(imgtool_image* img, UINT32 track,
799                UINT32 head, UINT32 sector,
800                UINT32 *sector_size)
801{
802  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
803 
804  if ( head >= f->heads || sector < 1 || sector > 16 || track >= f->tracks ) {
805    if ( sector_size ) *sector_size = 0;
806    return IMGTOOLERR_SEEKERROR;
807  }
808  if ( sector_size ) *sector_size = f->sector_size;
809  return IMGTOOLERR_SUCCESS;
810}
811
812static imgtoolerr_t thom_get_geometry(imgtool_image* img, UINT32* tracks,
813                  UINT32* heads, UINT32* sectors)
814{
815  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
816  if ( tracks ) *tracks = f->tracks;
817  if ( heads ) *heads = f->heads;
818  if ( sectors ) *sectors = 16;
819  return IMGTOOLERR_SUCCESS;
820}
821
822static imgtoolerr_t thom_read_sector(imgtool_image* img, UINT32 track,
823                 UINT32 head, UINT32 sector, void *buf,
824                 size_t len)
825{
826  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
827  if ( head >= f->heads || sector < 1 || sector > 16 || track >= f->tracks )
828    return IMGTOOLERR_SEEKERROR;
829  if ( len > f->sector_size) return IMGTOOLERR_READERROR;
830  memcpy( buf, thom_get_sector( f, head, track, sector ), len );
831  return IMGTOOLERR_SUCCESS;
832}
833
834static imgtoolerr_t thom_write_sector(imgtool_image *img, UINT32 track,
835                  UINT32 head, UINT32 sector,
836                  const void *buf, size_t len)
837{
838  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
839  if ( stream_isreadonly( f->stream ) ) return IMGTOOLERR_WRITEERROR;
840  if ( head >= f->heads || sector < 1 || sector > 16 || track >= f->tracks )
841    return IMGTOOLERR_SEEKERROR;
842  if ( len > f->sector_size) return IMGTOOLERR_WRITEERROR;
843  f->modified = 1;
844  memcpy( thom_get_sector( f, head, track, sector ), buf, len );
845  return IMGTOOLERR_SUCCESS;
846}
847
848/* returns floopy name */
849/* actually, each side has its own name, but we only return the one on side 0.
850 */
851static void thom_info(imgtool_image *img, char *string, size_t len)
852{
853  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
854  UINT8* base = thom_get_sector( f, 0, 20, 1 );
855  char buf[9];
856  memcpy( buf, base, 8 );
857  buf[8] = 0;
858  thom_stringify( buf );
859  strncpy( string, buf, len );
860}
861
862/* each side of a floppy has its own filesystem, we treat them as'partitions'
863 */
864static imgtoolerr_t thom_list_partitions(imgtool_image *img,
865                imgtool_partition_info *partitions,
866                size_t len)
867{
868  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
869  if ( len >= 1 ) {
870    partitions[0].get_info = thom_basic_get_info;
871    partitions[0].base_block = 0;
872    partitions[0].block_count = 1;
873  }
874  if ( len >= 2 && f->heads >= 2 ) {
875    partitions[1].get_info = thom_basic_get_info;
876    partitions[1].base_block = 1;
877    partitions[1].block_count = 1;
878  }
879  return IMGTOOLERR_SUCCESS;
880}
881
882static imgtoolerr_t thom_open_partition(imgtool_partition *part,
883               UINT64 first_block, UINT64 block_count)
884{
885  imgtool_image* img = imgtool_partition_image( part );
886  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
887  if ( first_block >= f->heads )
888    return IMGTOOLERR_INVALIDPARTITION;
889  * ( (int*) imgtool_partition_extra_bytes( part ) ) = first_block;
890  return IMGTOOLERR_SUCCESS;
891}
892
893
894static imgtoolerr_t thom_begin_enum(imgtool_directory *enumeration,
895                const char *path)
896{
897  int* n = (int*) imgtool_directory_extrabytes( enumeration );
898  *n = 0;
899  return IMGTOOLERR_SUCCESS;
900}
901
902static imgtoolerr_t thom_next_enum(imgtool_directory *enumeration,
903               imgtool_dirent *ent)
904{
905  imgtool_partition *part = imgtool_directory_partition( enumeration);
906  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
907  imgtool_image* img = imgtool_partition_image( part );
908  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
909  int* n = (int*) imgtool_directory_extrabytes( enumeration );
910  thom_dirent d;
911
912  do {
913    thom_get_dirent( f, head, *n, &d );
914    (*n) ++;
915  }
916  while ( d.type == THOM_DIRENT_FREE );
917  if ( d.type == THOM_DIRENT_END ) ent->eof = 1;
918  else if ( d.type == THOM_DIRENT_INVALID ) {
919    ent->corrupt = 1;
920  }
921  else {
922    int size;
923    snprintf( ent->filename, sizeof(ent->filename), "%s.%s", d.name, d.ext );
924    snprintf( ent->attr, sizeof(ent->attr), "%c %c %s",
925         (d.ftype == 0) ? 'B' :  (d.ftype == 1) ? 'D' :
926         (d.ftype == 2) ? 'M' :  (d.ftype == 3) ? 'A' : '?',
927         (d.format == 0) ? 'B' : (d.format == 0xff) ? 'A' : '?',
928         d.comment );
929    ent->creation_time = thom_crack_time( &d );
930    size  = thom_get_file_size( f, head, &d );
931    if ( size >= 0 ) ent->filesize = size;
932    else {
933      ent->filesize = 0;
934      ent->corrupt = 1;
935    }
936  }
937  return IMGTOOLERR_SUCCESS;
938}
939
940static imgtoolerr_t thom_free_space(imgtool_partition *part, UINT64 *size)
941{
942  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
943  imgtool_image* img = imgtool_partition_image( part );
944  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
945  int nb = thom_get_free_blocks( f, head );
946  (*size) = nb * f->sectuse_size * 8;
947  return IMGTOOLERR_SUCCESS;
948}
949
950static imgtoolerr_t thom_read_file(imgtool_partition *part,
951               const char *filename,
952               const char *fork,
953               imgtool_stream *destf)
954{
955  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
956  imgtool_image* img = imgtool_partition_image( part );
957  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
958  thom_dirent d;
959  char name[9], ext[4], fname[14];
960  int size;
961
962  /* convert filename */
963  thom_conv_filename( filename, name, ext );
964  sprintf( fname, "%s.%s", name, ext );
965
966  if ( ! thom_find_dirent( f, head, fname, &d ) )
967    return IMGTOOLERR_FILENOTFOUND;
968  size = thom_get_file_size( f, head, &d );
969  if ( size < 0 ) return IMGTOOLERR_CORRUPTFILE;
970  thom_get_file( f, head, &d, destf );
971  return IMGTOOLERR_SUCCESS;
972}
973
974static imgtoolerr_t thom_delete_file(imgtool_partition *part,
975                 const char *filename)
976{
977  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
978  imgtool_image* img = imgtool_partition_image( part );
979  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
980  thom_dirent d;
981  char name[9], ext[4], fname[14];
982
983  /* convert filename */
984  thom_conv_filename( filename, name, ext );
985  sprintf( fname, "%s.%s", name, ext );
986 
987  if ( ! thom_find_dirent( f, head, fname, &d ) )
988    return IMGTOOLERR_FILENOTFOUND;
989  /*if ( thom_get_file_size( f, head, &d ) < 0 ) return IMGTOOLERR_CORRUPTFILE;*/
990  if ( stream_isreadonly( f->stream ) ) return IMGTOOLERR_WRITEERROR;
991  thom_del_file( f, head, &d );
992  return IMGTOOLERR_SUCCESS;
993}
994
995static imgtoolerr_t thom_write_file(imgtool_partition *part,
996                const char *filename,
997                const char *fork,
998                imgtool_stream *sourcef,
999                option_resolution *opts)
1000{
1001  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
1002  imgtool_image* img = imgtool_partition_image( part );
1003  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
1004  thom_dirent d;
1005  int size = stream_size( sourcef );
1006  int blocks = thom_get_free_blocks( f, head );
1007  char name[9], ext[4], fname[14];
1008  const char* comment;
1009  int is_new = 1;
1010
1011  if ( stream_isreadonly( f->stream ) ) return IMGTOOLERR_WRITEERROR;
1012
1013  /* convert filename */
1014  thom_conv_filename( filename, name, ext );
1015  sprintf( fname, "%s.%s", name, ext );
1016
1017  /* check available space & find dir entry */
1018  if ( thom_find_dirent( f, head, fname, &d ) ) {
1019    /* file already exists: delete it */
1020    if ( thom_get_file_size( f, head, &d ) < 0 ) return IMGTOOLERR_CORRUPTFILE;
1021    blocks += thom_get_file_blocks( f, head, &d );
1022    if ( blocks * 8 * f->sectuse_size < size ) return IMGTOOLERR_NOSPACE;
1023    thom_del_file( f, head, &d );
1024    is_new = 0;
1025  }
1026  else {
1027    /* new file, need new dir entry */
1028    if ( blocks * 8 * f->sectuse_size < size ) return IMGTOOLERR_NOSPACE;
1029    if ( ! thom_find_free_dirent( f, head, &d ) ) return IMGTOOLERR_NOSPACE;
1030    thom_make_time_now( &d );
1031  }
1032
1033  /* fill-in dir entry */
1034  memcpy( d.name, name, 9 );
1035  memcpy( d.ext, ext, 4 );
1036
1037  /* file type */
1038  switch ( option_resolution_lookup_int( opts, 'T' ) ) {
1039  case 0:
1040    if ( ! is_new ) break;
1041    if ( ! mame_stricmp( ext, "BAS" ) ) d.ftype = 0;
1042    else if ( ! mame_stricmp( ext, "BAT" ) ) d.ftype = 0;
1043    else if ( ! mame_stricmp( ext, "DAT" ) ) d.ftype = 1;
1044    else if ( ! mame_stricmp( ext, "ASC" ) ) d.ftype = 1;
1045    else if ( ! mame_stricmp( ext, "BIN" ) ) d.ftype = 2;
1046    else if ( ! mame_stricmp( ext, "MAP" ) ) d.ftype = 2;
1047    else if ( ! mame_stricmp( ext, "CFG" ) ) d.ftype = 2;
1048    else if ( ! mame_stricmp( ext, "ASM" ) ) d.ftype = 3;
1049    else d.ftype = 2;
1050    break;
1051  case 1: d.ftype = 0; break;
1052  case 2: d.ftype = 1; break;
1053  case 3: d.ftype = 2; break;
1054  case 4: d.ftype = 3; break;
1055  }
1056
1057 /* format flag */
1058 switch ( option_resolution_lookup_int( opts, 'F' ) ) {
1059  case 0:
1060    if ( ! is_new ) break;
1061    if ( ! mame_stricmp( ext, "DAT" ) ) d.format = 0xff;
1062    else if ( ! mame_stricmp( ext, "ASC" ) ) d.format = 0xff;
1063    else if ( ! mame_stricmp( ext, "ASM" ) ) d.format = 0xff;
1064    else d.format = 0;
1065    break;
1066  case 1: d.format = 0; break;
1067  case 2: d.format = 0xff; break;
1068  }
1069 
1070 /* comment */
1071 comment = option_resolution_lookup_string( opts, 'C' );
1072 if ( comment && *comment )
1073   strncpy( d.comment, comment, 8 );
1074
1075  /* write file */
1076 thom_put_file( f, head, &d, sourcef );
1077 return IMGTOOLERR_SUCCESS;
1078}
1079
1080static imgtoolerr_t thom_suggest_transfer(imgtool_partition *part,
1081                 const char *fname,
1082                 imgtool_transfer_suggestion *suggestions,
1083                 size_t suggestions_length)
1084{
1085  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
1086  imgtool_image* img = imgtool_partition_image( part );
1087  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
1088  thom_dirent d;
1089  int is_basic = 0;
1090
1091  if ( suggestions_length < 1 ) return IMGTOOLERR_SUCCESS;
1092
1093  if ( fname ) {
1094    if ( ! thom_find_dirent( f, head, fname, &d ) )
1095      return IMGTOOLERR_FILENOTFOUND;
1096    if ( d.ftype == 0 && d.format == 0 ) is_basic = 1;
1097  }
1098
1099  if ( is_basic ) {
1100    suggestions[0].viability = SUGGESTION_RECOMMENDED;
1101    suggestions[0].filter = filter_thombas128_getinfo;
1102    if ( suggestions_length >= 2 ) {
1103      suggestions[1].viability = SUGGESTION_POSSIBLE;
1104      suggestions[1].filter = filter_thombas7_getinfo;
1105    }
1106    if ( suggestions_length >= 3 ) {
1107      suggestions[2].viability = SUGGESTION_POSSIBLE;
1108      suggestions[2].filter = filter_thombas5_getinfo;
1109    }
1110    if ( suggestions_length >= 4 ) {
1111      suggestions[3].viability = SUGGESTION_POSSIBLE;
1112      suggestions[3].filter = NULL;
1113    }
1114  }
1115  else {
1116    suggestions[0].viability = SUGGESTION_RECOMMENDED;
1117    suggestions[0].filter = NULL;
1118  }
1119
1120  return IMGTOOLERR_SUCCESS;
1121}
1122
1123static imgtoolerr_t thom_create(imgtool_image* img,
1124            imgtool_stream *stream,
1125            option_resolution *opts)
1126{
1127  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
1128  int i;
1129  UINT8* buf;
1130  const char* name;
1131
1132  f->stream = stream;
1133  f->modified = 0;
1134
1135  /* get parameters */
1136  f->heads = option_resolution_lookup_int( opts, 'H' );
1137  f->tracks = option_resolution_lookup_int( opts, 'T' );
1138  name = option_resolution_lookup_string( opts, 'N' );
1139  switch ( option_resolution_lookup_int( opts, 'D' ) ) {
1140  case 0: f->sector_size = 128; f->sectuse_size = 128; break;
1141  case 1: f->sector_size = 256; f->sectuse_size = 255; break;
1142  default: return IMGTOOLERR_PARAMCORRUPT;
1143  }
1144
1145  /* sanity checks */
1146  switch ( f->tracks ) {
1147  case 25: if ( f->sector_size != 128 ) return IMGTOOLERR_PARAMCORRUPT; break;
1148  case 40: break;
1149  case 80: if ( f->sector_size != 256 ) return IMGTOOLERR_PARAMCORRUPT; break;
1150  default: return IMGTOOLERR_PARAMCORRUPT;
1151  }
1152
1153  memset( f->data, 0xe5, sizeof( f->data ) );
1154
1155  for ( i = 0; i < f->heads; i++ ) {
1156
1157    /* disk info */
1158    buf = thom_get_sector( f, i, 20, 1 );
1159    memset( buf, 0xff, f->sector_size );
1160    if ( name ) {
1161      strncpy( (char*)buf, name, 8 );
1162      thom_unstringity( (char*)buf, 8 );
1163    }
1164    else memset( buf, ' ', 8 );
1165   
1166    /* FAT */
1167    buf = thom_get_sector( f, i, 20, 2 );
1168    memset( buf, 0, f->sector_size );
1169    memset( buf + 1, 0xff, thom_nb_blocks( f ) );
1170    buf[ 41 ] = buf[ 42 ] = 0xfe; /* reserved for FAT */
1171   
1172    /* (empty) directory */
1173    buf = thom_get_sector( f, i, 20, 3 );
1174    memset( buf, 0xff, 14 * f->sector_size );
1175  }
1176
1177  f->modified = 1;
1178
1179  return IMGTOOLERR_SUCCESS;
1180}
1181
1182
1183/****************** BASIC tokenization *********************/
1184
1185/* character codes >= 128 are reserved for BASIC keywords */
1186
1187static const char* thombas7[2][128] = {
1188  { /* statements */
1189    "END", "FOR", "NEXT", "DATA", "DIM", "READ", "LET", "GO", "RUN", "IF",
1190    "RESTORE", "RETURN", "REM", "'", "STOP", "ELSE", "TRON", "TROFF", "DEFSTR",
1191    "DEFINT", "DEFSNG", "DEFDBL", "ON", "WAIT", "ERROR", "RESUME", "AUTO",
1192    "DELETE", "LOCATE", "CLS", "CONSOLE", "PSET", "MOTOR", "SKIP", "EXEC",
1193    "BEEP", "COLOR", "LINE", "BOX", "UNMASK", "ATTRB", "DEF", "POKE", "PRINT",
1194    "CONT", "LIST", "CLEAR", "WHILE", "WHEN", "NEW", "SAVE", "LOAD", "MERGE",
1195    "OPEN", "CLOSE", "INPEN", "PEN", "PLAY", "TAB(", "TO", "SUB", "FN",
1196    "SPC(", "USING", "USR", "ERL", "ERR", "OFF", "THEN", "NOT", "STEP",
1197    "+", "-", "*", "/", "^", "AND", "OR", "XOR", "EQV", "IMP", "MOD", "@",
1198    ">", "=", "<",
1199    /* DOS specific */
1200    "DSKINI", "DSKO$", "KILL", "NAME", "FIELD", "LSET", "RSET",
1201    "PUT", "GET", "VERIFY", "DEVICE", "DIR", "FILES", "WRITE", "UNLOAD",
1202    "BACKUP", "COPY", "CIRCLE", "PAINT", "DRAW", "RENUM", "SWAP", "DENSITY",
1203  },
1204  { /* functions: 0xff prefix */
1205    "SGN", "INT", "ABS", "FRE", "SQR", "LOG", "EXP", "COS", "SIN",
1206    "TAN", "PEEK", "LEN", "STR$", "VAL", "ASC", "CHR$", "EOF", "CINT", "CSNG",
1207    "CDBL", "FIX", "HEX$", "OCT$", "STICK", "STRIG", "GR$", "LEFT$", "RIGHT$",
1208    "MID$", "INSTR", "VARPTR", "RND", "INKEY$", "INPUT", "CSRLIN", "POINT",
1209    "SCREEN", "POS", "PTRIG",
1210    /* DOS specific */
1211    "DSKL", "CVI", "CVS", "CVD", "MKI$", "MKS$", "MKD$", "LOC", "LOF",
1212    "SPACE$", "STRING$", "DSKI$",
1213  }
1214};
1215
1216/* MO5: some keywords ar missing; DOS and TUNE are added */
1217static const char* thombas5[2][128] = {
1218  { /* statements */
1219    "END", "FOR", "NEXT", "DATA", "DIM", "READ", NULL, "GO", "RUN", "IF",
1220    "RESTORE", "RETURN", "REM", "'", "STOP", "ELSE", "TRON", "TROFF", "DEFSTR",
1221    "DEFINT", "DEFSNG", NULL, "ON", "TUNE", "ERROR", "RESUME", "AUTO",
1222    "DELETE", "LOCATE", "CLS", "CONSOLE", "PSET", "MOTOR", "SKIP", "EXEC",
1223    "BEEP", "COLOR", "LINE", "BOX", NULL, "ATTRB", "DEF", "POKE", "PRINT",
1224    "CONT", "LIST", "CLEAR", "DOS", NULL, "NEW", "SAVE", "LOAD", "MERGE",
1225    "OPEN", "CLOSE", "INPEN", "PEN", "PLAY", "TAB(", "TO", "SUB", "FN",
1226    "SPC(", "USING", "USR", "ERL", "ERR", "OFF", "THEN", "NOT", "STEP",
1227    "+", "-", "*", "/", "^", "AND", "OR", "XOR", "EQV", "IMP", "MOD", "@",
1228    ">", "=", "<",
1229    /* DOS specific */
1230    "DSKINI", "DSKO$", "KILL", "NAME", "FIELD", "LSET", "RSET",
1231    "PUT", "GET", "VERIFY", "DEVICE", "DIR", "FILES", "WRITE", "UNLOAD",
1232    "BACKUP","COPY", "CIRCLE", "PAINT", "DRAW", "RENUM", "SWAP", "SEARCH",
1233    "DENSITY",
1234  },
1235  { /* functions: 0xff prefix */
1236    "SGN", "INT", "ABS", "FRE", "SQR", "LOG", "EXP", "COS", "SIN",
1237    "TAN", "PEEK", "LEN", "STR$", "VAL", "ASC", "CHR$", "EOF", "CINT", NULL,
1238    NULL, "FIX", "HEX$", NULL, "STICK", "STRIG", "GR$", "LEFT$", "RIGHT$",
1239    "MID$", "INSTR", "VARPTR", "RND", "INKEY$", "INPUT", "CSRLIN", "POINT",
1240    "SCREEN", "POS", "PTRIG",
1241    /* DOS specific */
1242    "DSKL", "CVI", "CVS", "CVD", "MKI$", "MKS$", "MKD$", "LOC", "LOF",
1243    "SPACE$", "STRING$", "DSKI$",
1244  }
1245};
1246
1247/* BASIC 128 has many new keywords */
1248/* DENSITY is missing on BASIC 512 & BASIC 128 for MO6 but, otherwise, they
1249   have the same tokens
1250*/
1251static const char* thombas128[2][128] = {
1252  { /* statements */
1253    "END", "FOR", "NEXT", "DATA", "DIM", "READ", "LET", "GO", "RUN", "IF",
1254    "RESTORE", "RETURN", "REM", "'", "STOP", "ELSE", "TRON", "TROFF", "DEFSTR",
1255    "DEFINT", "DEFSNG", "DEFDBL", "ON", "WAIT", "ERROR", "RESUME", "AUTO",
1256    "DELETE", "LOCATE", "CLS", "CONSOLE", "PSET", "MOTOR", "SKIP", "EXEC",
1257    "BEEP", "COLOR", "LINE", "BOX", "UNMASK", "ATTRB", "DEF", "POKE", "PRINT",
1258    "CONT", "LIST", "CLEAR", "INTERVAL", "KEY", "NEW", "SAVE", "LOAD", "MERGE",
1259    "OPEN", "CLOSE", "INPEN", "PEN", "PLAY", "TAB(", "TO", "SUB", "FN",
1260    "SPC(", "USING", "USR", "ERL", "ERR", "OFF", "THEN", "NOT", "STEP",
1261    "+", "-", "*", "/", "^", "AND", "OR", "XOR", "EQV", "IMP", "MOD", "@",
1262    ">", "=", "<",
1263    "DSKINI", "DSKO$", "KILL", "NAME", "FIELD", "LSET", "RSET",
1264    "PUT", "GET", "VERIFY", "DEVICE", "DIR", "FILES", "WRITE", "UNLOAD",
1265    "BACKUP", "COPY", "CIRCLE", "PAINT", "RESET", "RENUM", "SWAP", "DENSITY",
1266    "WINDOW", "PATTERN", "DO", "LOOP", "EXIT", "INMOUSE", "MOUSE", "CHAINE",
1267    "COMMON", "SEARCH", "FWD", "TURTLE",
1268  },
1269  { /* functions: 0xff prefix */
1270    "SGN", "INT", "ABS", "FRE", "SQR", "LOG", "EXP", "COS", "SIN",
1271    "TAN", "PEEK", "LEN", "STR$", "VAL", "ASC", "CHR$", "EOF", "CINT", "CSNG",
1272    "CDBL", "FIX", "HEX$", "OCT$", "STICK", "STRIG", "GR$", "LEFT$", "RIGHT$",
1273    "MID$", "INSTR", "VARPTR", "RND", "INKEY$", "INPUT", "CSRLIN", "POINT",
1274    "SCREEN", "POS", "PTRIG",
1275    "DSKL", "CVI", "CVS", "CVD", "MKI$", "MKS$", "MKD$", "LOC", "LOF",
1276    "SPACE$", "STRING$", "DSKI$",
1277    "FKEY$", "MIN(", "MAX(", "ATN", "CRUNCH$", "MTRIG", "EVAL", "PALETTE",
1278    "BANK", "HEAD", "ROT", "SHOW", "ZOOM", "TRACE",
1279  }
1280};
1281
1282/* tables for simple XOR encryption sieve */
1283static const UINT8 crypt1[11] = {
1284  0x80, 0x19, 0x56, 0xAA, 0x80, 0x76, 0x22, 0xF1,  0x82, 0x38, 0xAA
1285};
1286
1287static const UINT8 crypt2[13] = {
1288  0x86, 0x1E, 0xD7, 0xBA, 0x87, 0x99, 0x26, 0x64, 0x87, 0x23, 0x34, 0x58, 0x86
1289};
1290
1291/* decrypt BASIC protected files */
1292static void thom_decrypt(imgtool_stream* out, imgtool_stream* in)
1293{
1294  int i1 = 11, i2 = 13;
1295  while ( 1 ) {
1296    UINT8 b;
1297    if ( stream_read( in, &b, 1) < 1 ) break;
1298    b = ( (UINT8)(b - i2) ^ crypt2[i2-1] ^ crypt1[i1-1] ) + i1;
1299    stream_putc( out, b );
1300    i1--; i2--;
1301    if ( !i1 ) i1 = 11;
1302    if ( !i2 ) i2 = 13;
1303  }
1304}
1305
1306/* encrypt BASIC protected files */
1307static void thom_encrypt(imgtool_stream* out, imgtool_stream* in)
1308{
1309  int i1 = 11, i2 = 13;
1310  while ( 1 ) {
1311    UINT8 b;
1312    if ( stream_read( in, &b, 1) < 1 ) break;
1313    b = ( (UINT8)(b - i1) ^ crypt2[i2-1] ^ crypt1[i1-1] ) + i2;
1314    stream_putc( out, b );
1315    i1--; i2--;
1316    if ( !i1 ) i1 = 11;
1317    if ( !i2 ) i2 = 13;
1318  }
1319}
1320
1321static imgtoolerr_t thomcrypt_read_file(imgtool_partition *part,
1322               const char *name,
1323               const char *fork, imgtool_stream *dst)
1324{
1325  UINT8 buf[3];
1326  imgtool_stream *org = stream_open_mem( NULL, 0 );
1327  imgtoolerr_t err;
1328  if ( !org ) return IMGTOOLERR_OUTOFMEMORY;
1329
1330  /* read file */
1331  err = thom_read_file( part, name, fork, org );
1332  if ( err ) {
1333    stream_close( org );
1334    return err;
1335  }
1336
1337  stream_seek( org, 0, SEEK_SET );
1338  if ( stream_read( org, buf, 3 ) < 3 || buf[0] != 0xfe ) {
1339    /* regular file */
1340    stream_seek( org, 0, SEEK_SET );
1341    stream_transfer_all( dst, org );
1342  }
1343  else {
1344    /* encrypted file */
1345    stream_putc( dst, 0xff );
1346    stream_write( dst, buf+1, 2 );
1347    thom_decrypt( dst, org );
1348  }
1349
1350  stream_close( org );
1351  return IMGTOOLERR_SUCCESS;
1352}
1353
1354static imgtoolerr_t thomcrypt_write_file(imgtool_partition *part,
1355                const char *name,
1356                const char *fork, imgtool_stream *src,
1357                option_resolution *opts)
1358{
1359  UINT8 buf[3];
1360 
1361  if ( stream_read( src, buf, 3 ) < 3 || buf[0] == 0xfe ) {
1362    /* too short or already encrypted file */
1363    stream_seek( src, 0, SEEK_SET );
1364    return thom_write_file( part, name, fork, src, opts );
1365  }
1366  else {
1367    /* regular file */
1368    imgtool_stream *dst = stream_open_mem( NULL, 0 );
1369    imgtoolerr_t err;
1370    if ( !dst ) return IMGTOOLERR_OUTOFMEMORY;
1371    stream_putc( dst, 0xfe );
1372    stream_write( dst, buf+1, 2 );
1373    thom_encrypt( dst, src );
1374    stream_seek( dst, 0, SEEK_SET );
1375    err = thom_write_file( part, name, fork, dst, opts );
1376    stream_close( dst);
1377    return err;
1378  }
1379}
1380
1381void filter_thomcrypt_getinfo(UINT32 state, union filterinfo *info)
1382{
1383  switch(state) {
1384  case FILTINFO_STR_NAME:
1385    info->s = "thomcrypt";
1386    break;
1387  case FILTINFO_STR_HUMANNAME:
1388    info->s = "Thomson BASIC, Protected file encryption (no tokenization)";
1389    break;
1390  case FILTINFO_PTR_READFILE:
1391    info->read_file = thomcrypt_read_file;
1392    break;
1393  case FILTINFO_PTR_WRITEFILE:
1394    info->write_file = thomcrypt_write_file;
1395    break;
1396  }
1397}
1398
1399/* untokenization automatically decrypt protected files */
1400static imgtoolerr_t thom_basic_read_file(imgtool_partition *part,
1401                const char *name,
1402                const char *fork,
1403                imgtool_stream *dst,
1404                const char* table[2][128])
1405{
1406  imgtool_stream *org = stream_open_mem( NULL, 0 );
1407  imgtoolerr_t err;
1408  UINT8 buf[4];
1409  int i;
1410
1411  if ( !org ) return IMGTOOLERR_OUTOFMEMORY;
1412
1413  err = thomcrypt_read_file( part, name, fork, org );
1414  if ( err ) {
1415    stream_close( org );
1416    return err;
1417  }
1418  stream_seek( org, 3, SEEK_SET ); /* skip header */
1419
1420  while ( 1 ) {
1421    int in_str = 0, in_fun = 0;
1422    int linelength, linenum;
1423   
1424    /* line header: line length and line number */
1425    /* I am not sure this is 100% correct but it works in many cases */
1426    if ( stream_read( org, buf, 2 ) < 2 ) goto end;
1427    linelength = ((int)buf[0] << 8) + (int)buf[1] - 4;
1428    if ( linelength <= 0 ) goto end;
1429    if ( stream_read( org, buf, 2 ) < 2 ) goto end;
1430    linenum = ((int)buf[0] << 8) + buf[1];
1431    stream_printf( dst, "%u ", linenum );
1432
1433    /* process line */
1434    for ( i = 0; i < linelength; i++ ) {
1435      UINT8 c;
1436      if ( stream_read( org, &c, 1 ) < 1 ) break;
1437      if ( c == 0 ) {
1438   /* Sometimes, linelength seems wrong and we must rely on the fact that
1439      BASIC lines are 0-terminated.
1440      At other times, there are 0 embedded within lines or extra stuff
1441      between the 0 and the following line, and so, we must rely
1442      on linelength to cut the line (!)
1443   */
1444   if ( linelength > 256 ) break;
1445      }
1446      else if ( c == 0xff && ! in_str ) in_fun = 1; /* function prefix */
1447      else {
1448   if ( c >= 0x80 && ! in_str ) {
1449     /* token */
1450     const char* token = table[ in_fun ][ c - 0x80 ];
1451     if ( token ) stream_puts( dst, token );
1452     else stream_puts( dst, "???" );
1453   }
1454   else {
1455     /* regular character */
1456     if ( c == '"' ) in_str = 1 - in_str;
1457     stream_putc( dst, c ); /* normal letter */
1458   }
1459   in_fun = 0;
1460      }
1461    }
1462    stream_putc( dst, '\n' );
1463  }
1464  end:
1465
1466  stream_close( org );
1467  return IMGTOOLERR_SUCCESS;
1468}
1469
1470static imgtoolerr_t thom_basic_write_file(imgtool_partition *part,
1471                const char *name,
1472                const char *fork,
1473                imgtool_stream *src,
1474                option_resolution *opts,
1475                const char* table[2][128])
1476{
1477  return IMGTOOLERR_UNIMPLEMENTED;
1478}
1479
1480
1481#define FILTER(short,long)                  \
1482  static imgtoolerr_t short##_read_file(imgtool_partition *part,   \
1483               const char *name,      \
1484               const char *fork,      \
1485               imgtool_stream *dst)      \
1486  {                           \
1487    return thom_basic_read_file( part, name, fork, dst, short );   \
1488  }                           \
1489  static imgtoolerr_t short##_write_file(imgtool_partition *part,   \
1490                const char *name,      \
1491                const char *fork,      \
1492                imgtool_stream *src,      \
1493                option_resolution *opts)   \
1494  {                           \
1495    return thom_basic_write_file( part, name, fork, src, opts, short );   \
1496  }                           \
1497  void filter_##short##_getinfo(UINT32 state, union filterinfo *info)   \
1498  {                           \
1499    switch(state)                     \
1500      {                           \
1501      case FILTINFO_STR_NAME:                  \
1502   info->s = #short;                  \
1503   break;                        \
1504      case FILTINFO_STR_HUMANNAME:               \
1505   info->s = long;                     \
1506   break;                        \
1507      case FILTINFO_PTR_READFILE:               \
1508   info->read_file = short##_read_file;            \
1509   break;                        \
1510      case FILTINFO_PTR_WRITEFILE:               \
1511   info->write_file = short##_write_file;            \
1512   break;                        \
1513      }                           \
1514  }
1515
1516FILTER( thombas5,   
1517   "Thomson MO5 w/ BASIC 1.0, Tokenized Files (read-only, auto-decrypt)" )
1518FILTER( thombas7,   
1519   "Thomson TO7 w/ BASIC 1.0, Tokenized Files (read-only, auto-decrypt)" )
1520FILTER( thombas128,
1521   "Thomson w/ BASIC 128/512, Tokenized Files (read-only, auto-decrypt)" )
1522
1523
1524/************************* driver ***************************/
1525
1526OPTION_GUIDE_START( thom_createimage_optguide )
1527  OPTION_INT( 'H', "heads", "Heads" )
1528  OPTION_INT( 'T', "tracks", "Tracks" )
1529  OPTION_ENUM_START( 'D', "density", "Density" )
1530    OPTION_ENUM( 0, "SD", "Single density (128 bytes)" )
1531    OPTION_ENUM( 1, "DD", "Double density (256 bytes)" )
1532  OPTION_ENUM_END
1533  OPTION_STRING( 'N', "name", "Floppy name" )
1534OPTION_GUIDE_END
1535
1536OPTION_GUIDE_START( thom_writefile_optguide )
1537  OPTION_ENUM_START( 'T', "ftype", "File type" )
1538    OPTION_ENUM( 0, "auto", "Automatic (by extension)" )
1539    OPTION_ENUM( 1, "B", "Program" )
1540    OPTION_ENUM( 2, "D", "Data" )
1541    OPTION_ENUM( 3, "M", "Machine Code" )
1542    OPTION_ENUM( 4, "A",  "Assembler Source" )
1543  OPTION_ENUM_END
1544  OPTION_ENUM_START( 'F', "format", "Format flag" )
1545    OPTION_ENUM( 0, "auto",   "Automatic (by extension)" )
1546    OPTION_ENUM( 1, "B", "Binary, Tokenized BASIC" )
1547    OPTION_ENUM( 2, "A", "ASCII" )
1548  OPTION_ENUM_END
1549  OPTION_STRING( 'C', "comment", "Comment" )
1550OPTION_GUIDE_END
1551
1552static void thom_basic_get_info(const imgtool_class *clas,
1553            UINT32 param,
1554            union imgtoolinfo *info)
1555{
1556  switch ( param ) {
1557
1558  case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:
1559    info->i = sizeof(thom_floppy); break;
1560  case IMGTOOLINFO_INT_PARTITION_EXTRA_BYTES:
1561    info->i = sizeof(int); break;
1562  case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:
1563    info->i = sizeof(int); break;
1564  case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME:
1565  case IMGTOOLINFO_INT_PREFER_UCASE:
1566    info->i = 1; break;
1567  case IMGTOOLINFO_INT_PATH_SEPARATOR:
1568    info->i = 0; break;
1569  case IMGTOOLINFO_STR_FILE:
1570    strcpy( info->s = imgtool_temp_str(), __FILE__ ); break;
1571  case IMGTOOLINFO_STR_NAME:
1572    strcpy( info->s = imgtool_temp_str(), "thom" ); break;
1573  case IMGTOOLINFO_STR_DESCRIPTION:
1574    strcpy( info->s = imgtool_temp_str(), "Thomson BASIC filesystem" );
1575    break;
1576  case IMGTOOLINFO_PTR_CREATE:
1577    info->create = thom_create; break;
1578  case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:
1579    info->createimage_optguide = thom_createimage_optguide; break;
1580  case IMGTOOLINFO_PTR_BEGIN_ENUM:
1581    info->begin_enum = thom_begin_enum; break;
1582  case IMGTOOLINFO_PTR_NEXT_ENUM:
1583    info->next_enum = thom_next_enum; break;
1584  case IMGTOOLINFO_PTR_READ_FILE:
1585    info->read_file = thom_read_file; break;
1586  case IMGTOOLINFO_PTR_WRITE_FILE:
1587    info->write_file = thom_write_file; break;
1588  case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE:
1589    info->writefile_optguide = thom_writefile_optguide; break;
1590  case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC:
1591    strcpy( info->s = imgtool_temp_str(), "T[0]-4;F[0]-2;C" ); break;
1592  case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:
1593    info->suggest_transfer = thom_suggest_transfer; break;
1594  case IMGTOOLINFO_PTR_DELETE_FILE:
1595    info->delete_file = thom_delete_file; break;
1596  case IMGTOOLINFO_PTR_FREE_SPACE:
1597    info->free_space = thom_free_space; break;
1598  case IMGTOOLINFO_PTR_GET_SECTOR_SIZE:
1599    info->get_sector_size = thom_get_sector_size; break;
1600  case IMGTOOLINFO_PTR_GET_GEOMETRY:
1601    info->get_geometry = thom_get_geometry; break;
1602  case IMGTOOLINFO_PTR_INFO:
1603    info->info = thom_info; break;
1604  case IMGTOOLINFO_PTR_READ_SECTOR:
1605    info->read_sector = thom_read_sector; break;
1606  case IMGTOOLINFO_PTR_WRITE_SECTOR:
1607    info->write_sector = thom_write_sector; break;
1608  case IMGTOOLINFO_PTR_LIST_PARTITIONS:
1609    info->list_partitions = thom_list_partitions; break;
1610  case IMGTOOLINFO_PTR_OPEN_PARTITION:
1611    info->open_partition = thom_open_partition; break;
1612  }
1613}
1614
1615void thom_fd_basic_get_info(const imgtool_class *clas,
1616             UINT32 param,
1617             union imgtoolinfo *info)
1618{
1619  switch ( param ) {
1620  case IMGTOOLINFO_STR_NAME:
1621    strcpy( info->s = imgtool_temp_str(), "thom_fd" ); break;
1622  case IMGTOOLINFO_STR_DESCRIPTION:
1623    strcpy( info->s = imgtool_temp_str(),
1624       "Thomson .fd disk image, BASIC format" );
1625    break;
1626  case IMGTOOLINFO_STR_FILE_EXTENSIONS:
1627    strcpy( info->s = imgtool_temp_str(), "fd" ); break;
1628  case IMGTOOLINFO_PTR_OPEN:
1629    info->open = thom_open_fd_qd; break;
1630  case IMGTOOLINFO_PTR_CLOSE:
1631    info->close = thom_close_fd_qd; break;
1632  case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:
1633    strcpy( info->s = imgtool_temp_str(), "H[1]-2;T40/[80];D0-[1];N" ); break;
1634  default:
1635    thom_basic_get_info( clas, param, info );
1636  }
1637}
1638
1639void thom_qd_basic_get_info(const imgtool_class *clas,
1640             UINT32 param,
1641             union imgtoolinfo *info)
1642{
1643  switch ( param ) {
1644  case IMGTOOLINFO_STR_NAME:
1645    strcpy( info->s = imgtool_temp_str(), "thom_qd" ); break;
1646  case IMGTOOLINFO_STR_DESCRIPTION:
1647    strcpy( info->s = imgtool_temp_str(),
1648       "Thomson .qd disk image, BASIC format" );
1649    break;
1650  case IMGTOOLINFO_STR_FILE_EXTENSIONS:
1651    strcpy( info->s = imgtool_temp_str(), "qd" ); break;
1652  case IMGTOOLINFO_PTR_OPEN:
1653    info->open = thom_open_fd_qd; break;
1654  case IMGTOOLINFO_PTR_CLOSE:
1655    info->close = thom_close_fd_qd; break;
1656  case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:
1657    strcpy( info->s = imgtool_temp_str(), "H[1]-2;T[25];D[0];N" ); break;
1658  default:
1659    thom_basic_get_info( clas, param, info );
1660  }
1661}
1662
1663void thom_sap_basic_get_info(const imgtool_class *clas,
1664              UINT32 param,
1665              union imgtoolinfo *info)
1666{
1667  switch ( param ) {
1668  case IMGTOOLINFO_STR_NAME:
1669    strcpy( info->s = imgtool_temp_str(), "thom_sap" ); break;
1670  case IMGTOOLINFO_STR_DESCRIPTION:
1671    strcpy( info->s = imgtool_temp_str(),
1672       "Thomson .sap disk image, BASIC format" );
1673    break;
1674  case IMGTOOLINFO_STR_FILE_EXTENSIONS:
1675    strcpy( info->s = imgtool_temp_str(), "sap" ); break;
1676  case IMGTOOLINFO_PTR_OPEN:
1677    info->open = thom_open_sap; break;
1678  case IMGTOOLINFO_PTR_CLOSE:
1679    info->close = thom_close_sap; break;
1680  case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:
1681    strcpy( info->s = imgtool_temp_str(), "H[1];T40/[80];D0-[1];N" ); break;
1682  default:
1683    thom_basic_get_info( clas, param, info );
1684  }
1685}
src/mess/tools/imgtool/crt.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "zlib.h"
5#include "osdepend.h"
6#include "imgtoolx.h"
7
8#ifdef LSB_FIRST
9typedef struct {
10   unsigned char high, low;
11} biguword;
12typedef struct {
13   unsigned char highest, high, mid, low;
14} bigulong;
15#define GET_UWORD(a) (a.low|(a.high<<8))
16#define GET_ULONG(a) (a.low|(a.mid<<8)|(a.high<<16)|(a.highest<<24))
17#define SET_UWORD(a,v) a.low=(v)&0xff;a.high=((v)>>8)&0xff
18#define SET_ULONG(a,v) a.low=(v)&0xff;a.mid=((v)>>8)&0xff;a.high=((v)>>16)&0xff;a.highest=((v)>>24)&0xff
19#else
20typedef UINT32 bigulong;
21typedef UINT16 biguword;
22#define GET_UWORD(a) a
23#define GET_ULONG(a) a
24#define SET_UWORD(a,v) a=v
25#define SET_ULONG(a,v) a=v
26#endif
27
28/* format description found in the ccs64 emulator
29
30CARTRIDGE FILE FORMAT FOR CCS64 (using fileextension .CRT)
31
320000 'C64 CARTRIDGE '
330010 ULONG fileheader-length (counted from offset 0000, default=0040)
340014 UWORD Version (=0100)
350016 UWORD Hardware type
360018 UBYTE Exrom line
370019 UBYTE Game line
38001A UBYTE[6] For future use...
390020 UBYTE[20] Name (null-terminated string)
400040 Chip Packets
41...
42
43Chip Packets:
44
450000 'CHIP'
460004 ULONG packetlength (counted from offset 0000)
470008 UWORD chiptype
48000A UWORD bank (for normal cartridges = 0)
49000C UWORD address
50000E UWORD length
510010 UBYTE[] data
52...
53Hardware Types:
54
550 - Normal cartridge
561 - Action Replay
572 - KCS Power Cartridge
583 - Final Cartridge III
594 - Simons Basic
605 - Ocean type 1 (256 and 128 Kb)
616 - Expert Cartridge
627 - Fun Play
638 - Super Games
649 - Atomic Power
6510 - Epyx Fastload
6611 - Westermann
67
68
69Chip Types:
70
710 - ROM
721 - RAM, no data field
732 - Flash ROM
74
75
76All UWORD and ULONG's are in (MSB,LSB) format, i.e. $1234 will be $12,$34 in bytes.
77
78EXAMPLE FOR ACTION REPLAY CARTRIDGE
79
80$0000: 'C64 CARTRIDGE   '
81$0010: 00 00 00 40  01 00 00 01  00 00 00 00  00 00 00 00
82$0020: 'Action Replay V' 00
83$0030: 00 00 ... 00
84
85$0040: 'CHIP'
86$0044: 00 00 20 10  00 00 00 00  80 00 20 00
87$0050: <data 8192 bytes for bank 0>...
88
89$2050: 'CHIP'
90$2054: 00 00 20 10  00 00 00 01  80 00 20 00
91$2060: <data 8192 bytes for bank 1>...
92
93$4060: 'CHIP'
94$4064: 00 00 20 10  00 00 00 02  80 00 20 00
95$4070: <data 8192 bytes for bank 2>...
96
97$6070: 'CHIP'
98$6074: 00 00 20 10  00 00 00 03  80 00 20 00
99$6080: <data 8192 bytes for bank 3>...
100
101$8080:
102
103 
104
105EXAMPLE FOR KCS POWER CARTRIDGE
106
107$0000: 'C64 CARTRIDGE   '
108$0010: 00 00 00 40  01 00 00 02  00 00 00 00  00 00 00 00
109$0020: 'KCS Power Cartridge' 00
110$0030: 00 00 ... 00
111
112$0040: 'CHIP'
113$0044: 00 00 20 10  00 00 00 00  80 00 20 00
114$0050: <data 8192 bytes for 8000-9fff>...
115
116$2050: 'CHIP'
117$2054: 00 00 20 10  00 00 00 00  A0 00 20 00
118$2060: <data 8192 bytes for a000-bfff>...
119
120$4060:
121
122 
123
124EXAMPLE FOR FINAL CARTRIDGE III
125
126$0000: 'C64 CARTRIDGE   '
127$0010: 00 00 00 40  01 00 00 03  01 01 00 00  00 00 00 00
128$0020: 'Final cartridge' 00
129$0030: 00 00 ... 00
130
131$0040: 'CHIP'
132$0044: 00 00 40 10  00 00 00 00  80 00 40 00
133$0050: <data 16384 bytes for bank 0>...
134
135$4050: 'CHIP'
136$4054: 00 00 40 10  00 00 00 01  80 00 40 00
137$4060: <data 16384 bytes for bank 1>...
138
139$8060: 'CHIP'
140$8064: 00 00 40 10  00 00 00 02  80 00 40 00
141$8070: <data 16384 bytes for bank 2>...
142
143$C070: 'CHIP'
144$C074: 00 00 40 10  00 00 00 03  80 00 40 00
145$C080: <data 16384 bytes for bank 3>...
146
147$10080:
148
149 
150
151EXAMPLE FOR SIMONS BASIC
152
153$0000: 'C64 CARTRIDGE   '
154$0010: 00 00 00 40  01 00 00 04  00 01 00 00  00 00 00 00
155$0020: 'Simons Basic' 00
156$0030: 00 00 ... 00
157
158$0040: 'CHIP'
159$0044: 00 00 20 10  00 00 00 00  80 00 20 00
160$0050: <data 8192 bytes for 8000-9fff>...
161
162$2050: 'CHIP'
163$2054: 00 00 20 10  00 00 00 00  A0 00 20 00
164$2060: <data 8192 bytes for a000-bfff>...
165
166$4060:
167
168 
169
170EXAMPLE FOR OCEAN TYPE1
171
172$0000: 'C64 CARTRIDGE   '
173$0010: 00 00 00 40  01 00 00 05  00 00 00 00  00 00 00 00
174$0020: 'Robocop2' 00
175$0030: 00 00 ... 00
176
177$0040: 'CHIP'
178$0044: 00 00 20 10  00 00 00 00  80 00 20 00
179$0050: <data 8192 bytes for 8000-9fff, bank 0>...
180
181$2050: 'CHIP'
182$2054: 00 00 20 10  00 00 00 01  80 00 20 00
183$2060: <data 8192 bytes for 8000-9fff, bank 1>...
184...
185$20140: 'CHIP'
186$20144: 00 00 20 10  00 00 00 10  A0 00 20 00
187$20150: <data 8192 bytes for a000-bfff, bank 16>...
188
189$22150: 'CHIP'
190$22154: 00 00 20 10  00 00 00 11  A0 00 20 00
191$22160: <data 8192 bytes for a000-bfff, bank 17>...
192...
193$40240:
194
195 
196
197EXAMPLE FOR FUN PLAY TYPE
198
199$0000: 'C64 CARTRIDGE '
200$0010: 00 00 00 40 01 00 00 07 00 00 00 00 00 00 00 00
201$0020: 'FUN PLAY' 00 00 00 00 00 00 00 00
202$0030: 00 00 ... 00
203
204$0040: 'CHIP'
205$0044: 00 00 20 10 00 00 00 00 80 00 20 00
206$0050: <data 8192 bytes for 8000-9fff, bank 0>...
207
208$2050: 'CHIP'
209$2054: 00 00 20 10 00 00 00 08 80 00 20 00
210$2060: <data 8192 bytes for 8000-9fff, bank 1>...
211
212$4060: 'CHIP'
213$2054: 00 00 20 10 00 00 00 10 80 00 20 00
214$2060: <data 8192 bytes for 8000-9fff, bank 2>...
215...
216
217$1E130: 'CHIP'
218$1E134: 00 00 20 10 00 00 00 39 80 00 20 00
219$1E140: <data 8192 bytes for 8000-9fff, bank 15>...
220
221$20140:
222
223 
224
225EXAMPLE FOR SUPER GAMES TYPE
226
227$0000: 'C64 CARTRIDGE '
228$0010: 00 00 00 40 01 00 00 08 00 00 00 00 00 00 00 00
229$0020: 'SUPER GAMES' 00 00 00 00 00
230$0030: 00 00 ... 00
231
232$0040: 'CHIP'
233$0044: 00 00 40 10 00 00 00 00 80 00 40 00
234$0050: <data 16384 bytes for 8000-bfff, bank 0>...
235
236$4050: 'CHIP'
237$4054: 00 00 40 10 00 00 00 01 80 00 40 00
238$4060: <data 16384 bytes for 8000-bfff, bank 0>...
239
240$8060: 'CHIP'
241$8064: 00 00 40 10 00 00 00 02 80 00 40 00
242$8070: <data 16384 bytes for 8000-bfff, bank 0>...
243
244$C070: 'CHIP'
245$C074: 00 00 40 10 00 00 00 03 80 00 40 00
246$C080: <data 16384 bytes for 8000-bfff, bank 0>...
247
248$10080:
249
250 
251
252EXAMPLE FOR ATOMIC POWER CARTRIDGE
253
254$0000: 'C64 CARTRIDGE   '
255$0010: 00 00 00 40  01 00 00 09  00 00 00 00  00 00 00 00
256$0020: 'Atomic Power' 00
257$0030: 00 00 ... 00
258
259$0040: 'CHIP'
260$0044: 00 00 20 10  00 00 00 00  80 00 20 00
261$0050: <data 8192 bytes for bank 0>...
262
263$2050: 'CHIP'
264$2054: 00 00 20 10  00 00 00 01  80 00 20 00
265$2060: <data 8192 bytes for bank 1>...
266
267$4060: 'CHIP'
268$4064: 00 00 20 10  00 00 00 02  80 00 20 00
269$4070: <data 8192 bytes for bank 2>...
270
271$6070: 'CHIP'
272$6074: 00 00 20 10  00 00 00 03  80 00 20 00
273$6080: <data 8192 bytes for bank 3>...
274
275$8080:
276
277 
278
279EXAMPLE FOR EPYX FASTLOAD TYPE
280
281$0000: 'C64 CARTRIDGE '
282$0010: 00 00 00 40 01 00 00 0A 01 01 00 00 00 00 00 00
283$0020: 'EPYX FASTLOAD' 00 00 00
284$0030: 00 00 ... 00
285
286$0040: 'CHIP'
287$0044: 00 00 20 10 00 00 00 00 80 00 20 00
288$0050: <data 8192 bytes for 8000-9fff>
289
290$2050:
291
292 
293
294EXAMPLE FOR WESTERMANN TYPE
295
296$0000: 'C64 CARTRIDGE '
297$0010: 00 00 00 40 01 00 00 0A 00 01 00 00 00 00 00 00
298$0020: 'Westermann' 00 00 00
299$0030: 00 00 ... 00
300
301$0040: 'CHIP'
302$0044: 00 00 40 10 00 00 00 00 80 00 40 00
303$0050: <data 16384 bytes for 8000-bfff>
304
305$4050:
306*/
307 
308static const char *hardware_types[]={
309   "Normal cartridge",
310   "Action Replay",
311   "KCS Power Cartridge",
312   "Final Cartridge III",
313   "Simons Basic",
314   "Ocean type 1 (256 and 128 Kb)",
315   "Expert Cartridge",
316   "Fun Play",
317   "Super Games",
318   "Atomic Power",
319   "Epyx Fastload",
320   "Westermann"
321};
322typedef struct{
323   char id[0x10]; // C64 CARTRIDGE
324   bigulong length;
325   biguword version;
326   biguword hardware_type;
327   unsigned char exrom_line;
328   unsigned char game_line;
329   unsigned char reserved[6];
330   char name[0x20];
331} crt_header;
332   
333static const char *chip_types[]={ "ROM", "RAM", "FLASH" };
334typedef struct {
335   char id[4]; // CHIP
336   bigulong packet_length;
337   biguword chip_type;
338   biguword bank;
339   biguword address;
340   biguword length;
341} crt_packet;
342
343typedef struct {
344   imgtool_image base;
345   imgtool_stream *file_handle;
346   int size;
347   int modified;
348   unsigned char *data;
349} crt_image;
350
351#define HEADER(image) ((crt_header*)image->data)
352#define PACKET(image, pos) ((crt_packet*)(image->data+pos))
353
354typedef struct {
355   imgtool_directory base;
356   crt_image *image;
357   int pos;
358   int number;
359} crt_iterator;
360
361static int crt_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
362static void crt_image_exit(imgtool_image *img);
363static void crt_image_info(imgtool_image *img, char *string, const int len);
364static int crt_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
365static int crt_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
366static void crt_image_closeenum(imgtool_directory *enumeration);
367//static size_t crt_image_freespace(imgtool_image *img);
368static int crt_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
369static int crt_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *_options);
370static int crt_image_deletefile(imgtool_image *img, const char *fname);
371static int crt_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options);
372
373/*
374   IMAGE_USES_FTYPE|IMAGE_USES_FADDR|IMAGE_USES_FBANK
375   |IMAGE_USES_HARDWARE_TYPE|IMAGE_USES_GAME_LINE
376   |IMAGE_USES_EXROM_LINE|IMAGE_USES_LABEL, //flags
377*/
378
379static struct OptionTemplate c64crt_fileeopts[] =
380{
381   { "ftype",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,   0,      0xffff,   NULL   },   /* [0] */
382   { "faddr",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,   0,      0xffff,   NULL   },   /* [1] */
383   { "fbank",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,   0,      0xffff,   NULL   },   /* [2] */
384   { NULL, NULL, 0, 0, 0, 0 }
385};
386
387#define C64CRT_FILEOPTION_FTYPE      0
388#define C64CRT_FILEOPTION_FADDR      1
389#define C64CRT_FILEOPTION_FBANK      2
390
391static struct OptionTemplate c64crt_createopts[] =
392{
393   { "hardwaretype",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      0xffff,   NULL   },   /* [0] */
394   { "gameline",      NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      0x00ff,   NULL   },   /* [1] */
395   { "exromline",      NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      0x00ff,   NULL   },   /* [2] */
396   { "label",         NULL, IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,   0,      0,      NULL   },   /* [3] */
397   { NULL, NULL, 0, 0, 0, 0 }
398};
399
400#define C64CRT_CREATEOPTION_HARDWARETYPE   0
401#define C64CRT_CREATEOPTION_GAMELINE      1
402#define C64CRT_CREATEOPTION_EXROMLINE      2
403#define C64CRT_CREATEOPTION_LABEL         3
404
405IMAGEMODULE(
406   c64crt,
407   "Commodore 64 Cartridge",   /* human readable name */
408   "crt",                        /* file extension */
409   "c64.crc",                        /* crcfile */
410   "c64",                        /* crc system name */
411   NULL,                        /* eoln */
412   0,                           /* flags */
413   crt_image_init,            /* init function */
414   crt_image_exit,            /* exit function */
415   crt_image_info, /* info function */
416   crt_image_beginenum,         /* begin enumeration */
417   crt_image_nextenum,         /* enumerate next */
418   crt_image_closeenum,         /* close enumeration */
419   NULL, //crt_image_freespace,         /* free space on image */
420   crt_image_readfile,         /* read file */
421   crt_image_writefile,         /* write file */
422   crt_image_deletefile,         /* delete file */
423   crt_image_create,            /* create image */
424   NULL,                        /* read sector */
425   NULL,                        /* write sector */
426   c64crt_fileeopts,               /* file _options */
427   c64crt_createopts               /* create options */
428)
429
430static int crt_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
431{
432   crt_image *image;
433
434   image=*(crt_image**)outimg=(crt_image *) malloc(sizeof(crt_image));
435   if (!image) return IMGTOOLERR_OUTOFMEMORY;
436
437   memset(image, 0, sizeof(crt_image));
438   image->base.module = mod;
439   image->size=stream_size(f);
440   image->file_handle=f;
441
442   image->data = (unsigned char *) malloc(image->size);
443   if ( (!image->data)
444       ||(stream_read(f, image->data, image->size)!=image->size) ) {
445      free(image);
446      *outimg=NULL;
447      return IMGTOOLERR_OUTOFMEMORY;
448   }
449
450   return 0;
451}
452
453static void crt_image_exit(imgtool_image *img)
454{
455   crt_image *image=(crt_image*)img;
456   if (image->modified) {
457      stream_clear(image->file_handle);
458      stream_write(image->file_handle, image->data, image->size);
459   }
460   stream_close(image->file_handle);
461   free(image->data);
462   free(image);
463}
464
465static void crt_image_info(imgtool_image *img, char *string, const int len)
466{
467   crt_image *image=(crt_image*)img;
468   sprintf(string, "%-32s\nversion:%.4x type:%d:%s exrom:%d game:%d",
469         HEADER(image)->name,
470         GET_UWORD(HEADER(image)->version),
471         GET_UWORD(HEADER(image)->hardware_type),
472         hardware_types[GET_UWORD(HEADER(image)->hardware_type)],
473         HEADER(image)->exrom_line, HEADER(image)->game_line);
474   return;
475}
476
477static int crt_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
478{
479   crt_image *image=(crt_image*)img;
480   crt_iterator *iter;
481
482   iter=*(crt_iterator**)outenum = (crt_iterator *) malloc(sizeof(crt_iterator));
483   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
484
485   iter->base.module = img->module;
486
487   iter->image=image;
488   iter->pos = GET_ULONG( HEADER(image)->length );
489   iter->number = 0;
490   return 0;
491}
492
493static int crt_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
494{
495   crt_iterator *iter=(crt_iterator*)enumeration;
496
497   ent->corrupt=0;
498   
499   if (!(ent->eof=(iter->pos>=iter->image->size))) {
500      sprintf(ent->fname,"%d", iter->number);
501      ent->filesize=GET_UWORD( PACKET(iter->image, iter->pos)->length );
502      if (ent->attr) {
503          unsigned crc=crc32(0, iter->image->data+iter->pos+sizeof(crt_packet), ent->filesize);
504         sprintf(ent->attr,"%-4s %s bank:%-2d addr:%.4x crc:%8x",
505               (char*)PACKET(iter->image, iter->pos),
506               chip_types[GET_UWORD(PACKET(iter->image,iter->pos)->chip_type)],
507               GET_UWORD( PACKET(iter->image,iter->pos)->bank),
508               GET_UWORD( PACKET(iter->image,iter->pos)->address),
509            crc);
510      }
511      iter->number++;
512
513      iter->pos+=GET_ULONG( PACKET(iter->image, iter->pos)->packet_length );
514   }
515   return 0;
516}
517
518static void crt_image_closeenum(imgtool_directory *enumeration)
519{
520   free(enumeration);
521}
522
523#if 0
524static size_t crt_image_freespace(imgtool_image *img)
525{
526   int i;
527   rsdos_diskimage *rsimg = (rsdos_diskimage *) img;
528   size_t s = 0;
529
530   for (i = 0; i < GRANULE_COUNT; i++)
531      if (rsimg->granulemap[i] == 0xff)
532         s += (9 * 256);
533   return s;
534}
535#endif
536
537static int crt_image_findfile(crt_image *image, const char *fname)
538{
539   int nr=0;
540   char name[6];
541   int i=sizeof(crt_header);
542
543   while (i<image->size) {
544      sprintf(name, "%d",nr);
545      if (!strcmp(fname, name) ) return i;
546      i+=GET_ULONG( PACKET(image, i)->packet_length );
547      nr++;
548   }
549   return 0;
550}
551
552static int crt_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
553{
554   crt_image *image=(crt_image*)img;
555   int size;
556   int pos;
557
558   if (!(pos=crt_image_findfile(image, fname)) )
559      return IMGTOOLERR_MODULENOTFOUND;
560
561   size=GET_UWORD( PACKET(image, pos)->length );
562   if (stream_write(destf, image->data+pos+sizeof(crt_packet), size)!=size) {
563      return IMGTOOLERR_WRITEERROR;
564   }
565
566   return 0;
567}
568
569static int crt_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef,
570                        const ResolvedOption *_options)
571{
572   crt_image *image=(crt_image*)img;
573   int size;
574   int pos;
575
576   size=stream_size(sourcef);
577   if (!(pos=crt_image_findfile(image, fname)) ) {
578      // appending
579      pos=image->size;
580      if (!(image->data=realloc(image->data, image->size+size+sizeof(crt_packet))) )
581         return IMGTOOLERR_OUTOFMEMORY;
582      image->size+=size+sizeof(crt_packet);
583   } else {
584      int oldsize=GET_ULONG(PACKET(image,pos)->packet_length);
585      // overwritting
586      if (!(image->data=realloc(image->data, image->size+size+sizeof(crt_packet)-oldsize) ) )
587         return IMGTOOLERR_OUTOFMEMORY;
588      if (image->size-pos-oldsize!=0) {
589         memmove(image->data+pos+size+sizeof(crt_packet), image->data+pos+oldsize,
590               image->size-pos-oldsize);
591      }
592      image->size+=size+sizeof(crt_packet)-oldsize;
593   }
594   if (stream_read(sourcef, image->data+pos+sizeof(crt_packet), size)!=size) {
595      return IMGTOOLERR_READERROR;
596   }
597   memset(image->data+pos, 0, sizeof(crt_packet));
598   memcpy(PACKET(image,pos)->id,"CHIP",4);
599   SET_ULONG( PACKET(image, pos)->packet_length, size+sizeof(crt_packet));
600   SET_UWORD(PACKET(image, pos)->chip_type, _options[C64CRT_FILEOPTION_FTYPE].i);
601   SET_UWORD( PACKET(image, pos)->address, _options[C64CRT_FILEOPTION_FADDR].i);
602   SET_UWORD( PACKET(image, pos)->bank, _options[C64CRT_FILEOPTION_FBANK].i);
603   SET_UWORD( PACKET(image, pos)->length, size);
604
605   image->modified=1;
606
607   return 0;
608}
609
610static int crt_image_deletefile(imgtool_image *img, const char *fname)
611{
612   crt_image *image=(crt_image*)img;
613   int size;
614   int pos;
615
616   if (!(pos=crt_image_findfile(image, fname)) ) {
617      return IMGTOOLERR_MODULENOTFOUND;
618   }
619   size=GET_ULONG(PACKET(image, pos)->packet_length);
620   if (image->size-pos-size>0)
621      memmove(image->data+pos, image->data+pos+size, image->size-pos-size);
622   image->size-=size;
623   image->modified=1;
624
625   return 0;
626}
627
628static int crt_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options)
629{
630   crt_header header={ "C64 CARTRIDGE   " };
631   SET_ULONG(header.length, sizeof(header));
632   SET_UWORD(header.version, 0x100);
633   SET_UWORD(header.hardware_type, _options[C64CRT_CREATEOPTION_HARDWARETYPE].i);
634   header.game_line=_options[C64CRT_CREATEOPTION_GAMELINE].i;
635   header.exrom_line=_options[C64CRT_CREATEOPTION_EXROMLINE].i;
636   if (_options[C64CRT_CREATEOPTION_LABEL].s) strcpy(header.name, _options[C64CRT_CREATEOPTION_LABEL].s);
637   return (stream_write(f, &header, sizeof(crt_header)) == sizeof(crt_header))
638      ? 0 : IMGTOOLERR_WRITEERROR;
639}
640
src/mess/tools/imgtool/macbin.c
r1339r1340
1/****************************************************************************
2
3   macbin.c
4
5   MacBinary filter for use with Mac and ProDOS drivers
6
7*****************************************************************************
8
9  MacBinary file format
10
11  Offset  Length  Description
12  ------  ------  -----------
13       0       1  [I]   Magic byte (0x00)
14      1      64  [I]   File name (Pascal String)
15      65       4  [I]   File Type Code
16     69       4  [I]   File Creator Code
17     73       1  [I]   Finder Flags (bits 15-8)
18     74       1  [I]   Magic byte (0x00)
19     75       2  [I]   File Vertical Position
20     77       2  [I]   File Horizontal Position
21     79       2  [I]   Window/Folder ID
22     81       1  [I]   Protected (bit 0)
23     82       1  [I]   Magic byte (0x00)
24     83       4  [I]   Data Fork Length
25     87       4  [I]   Resource Fork Length
26     91       4  [I]   Creation Date
27     95       4  [I]   Last Modified Date
28     99       2  [I]   "Get Info" comment length
29     101       1  [II]  Finder Flags (bits 7-0)
30    102       4  [III] MacBinary III Signature 'mBIN'
31    106       1  [III] Script of Filename
32    107       1  [III] Extended Finder Flags
33    116       4  [II]  Unpacked Length
34    120       2  [II]  Secondary Header Length
35    122       1  [II]  MacBinary II Version Number (II: 0x81, III: 0x82)
36    123       1  [II]  Minimum Compatible MacBinary II Version Number (0x81)
37    124       2  [II]  CRC of previous 124 bytes 
38   
39   For more information, consult http://www.lazerware.com/formats/macbinary.html
40
41   TODO: I believe that the script code is some sort of identifier identifying
42   the character set used for the filename.  If this is true, we are not
43   handling that properly
44
45*****************************************************************************/
46
47#include <string.h>
48
49#include "imgtool.h"
50#include "macutil.h"
51
52
53
54static UINT32 pad128(UINT32 length)
55{
56   if (length % 128)
57      length += 128 - (length % 128);
58   return length;
59}
60
61
62
63static imgtoolerr_t macbinary_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
64{
65   static const UINT32 attrs[] =
66   {
67      IMGTOOLATTR_TIME_CREATED,
68      IMGTOOLATTR_TIME_LASTMODIFIED,
69      IMGTOOLATTR_INT_MAC_TYPE,
70      IMGTOOLATTR_INT_MAC_CREATOR,
71      IMGTOOLATTR_INT_MAC_FINDERFLAGS,
72      IMGTOOLATTR_INT_MAC_COORDX,
73      IMGTOOLATTR_INT_MAC_COORDY,
74      IMGTOOLATTR_INT_MAC_FINDERFOLDER,
75      IMGTOOLATTR_INT_MAC_SCRIPTCODE,
76      IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS,
77      0
78   };
79   imgtoolerr_t err;
80   UINT8 header[128];
81   const char *basename;
82   int i;
83
84   UINT32 type_code = 0x3F3F3F3F;
85   UINT32 creator_code = 0x3F3F3F3F;
86   UINT16 finder_flags = 0;
87   UINT16 coord_x = 0;
88   UINT16 coord_y = 0;
89   UINT16 finder_folder = 0;
90   UINT8 script_code = 0;
91   UINT8 extended_flags = 0;
92
93   imgtool_forkent fork_entries[4];
94   const imgtool_forkent *data_fork = NULL;
95   const imgtool_forkent *resource_fork = NULL;
96   UINT32 creation_time = 0;
97   UINT32 lastmodified_time = 0;
98   imgtool_attribute attr_values[10];
99
100   /* get the forks */
101   err = imgtool_partition_list_file_forks(partition, filename, fork_entries, sizeof(fork_entries));
102   if (err)
103      return err;
104   for (i = 0; fork_entries[i].type != FORK_END; i++)
105   {
106      if (fork_entries[i].type == FORK_DATA)
107         data_fork = &fork_entries[i];
108      else if (fork_entries[i].type == FORK_RESOURCE)
109         resource_fork = &fork_entries[i];
110   }
111
112   /* get the attributes */
113   err = imgtool_partition_get_file_attributes(partition, filename, attrs, attr_values);
114   if (err && (ERRORCODE(err) != IMGTOOLERR_UNIMPLEMENTED))
115      return err;
116   if (err == IMGTOOLERR_SUCCESS)
117   {
118      creation_time     = mac_setup_time(attr_values[0].t);
119      lastmodified_time = mac_setup_time(attr_values[1].t);
120      type_code         = attr_values[2].i;
121      creator_code      = attr_values[3].i;
122      finder_flags      = attr_values[4].i;
123      coord_x           = attr_values[5].i;
124      coord_y           = attr_values[6].i;
125      finder_folder     = attr_values[7].i;
126      script_code       = attr_values[8].i;
127      extended_flags    = attr_values[9].i;
128   }
129
130   memset(header, 0, sizeof(header));
131
132   /* place filename */
133   basename = filename;
134   while(basename[strlen(basename) + 1])
135      basename += strlen(basename) + 1;
136   pascal_from_c_string((unsigned char *) &header[1], 64, basename);
137
138   place_integer_be(header,  65, 4, type_code);
139   place_integer_be(header,  69, 4, creator_code);
140   place_integer_be(header,  73, 1, (finder_flags >> 8) & 0xFF);
141   place_integer_be(header,  75, 2, coord_x);
142   place_integer_be(header,  77, 2, coord_y);
143   place_integer_be(header,  79, 2, finder_folder);
144   place_integer_be(header,  83, 4, data_fork ? data_fork->size : 0);
145   place_integer_be(header,  87, 4, resource_fork ? resource_fork->size : 0);
146   place_integer_be(header,  91, 4, creation_time);
147   place_integer_be(header,  95, 4, lastmodified_time);
148   place_integer_be(header, 101, 1, (finder_flags >> 0) & 0xFF);
149   place_integer_be(header, 102, 4, 0x6D42494E);
150   place_integer_be(header, 106, 1, script_code);
151   place_integer_be(header, 107, 1, extended_flags);
152   place_integer_be(header, 122, 1, 0x82);
153   place_integer_be(header, 123, 1, 0x81);
154   place_integer_be(header, 124, 2, ccitt_crc16(0, header, 124));
155
156   stream_write(destf, header, sizeof(header));
157   
158   if (data_fork)
159   {
160      err = imgtool_partition_read_file(partition, filename, "", destf, NULL);
161      if (err)
162         return err;
163
164      stream_fill(destf, 0, pad128(data_fork->size));
165   }
166   
167   if (resource_fork)
168   {
169      err = imgtool_partition_read_file(partition, filename, "RESOURCE_FORK", destf, NULL);
170      if (err)
171         return err;
172
173      stream_fill(destf, 0, pad128(resource_fork->size));
174   }
175
176   return IMGTOOLERR_SUCCESS;
177}
178
179
180
181static imgtoolerr_t write_fork(imgtool_partition *partition, const char *filename, const char *fork,
182   imgtool_stream *sourcef, UINT64 pos, UINT64 fork_len, option_resolution *opts)
183{
184   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
185   imgtool_stream *mem_stream = NULL;
186   size_t len;
187
188   if (fork_len > 0)
189   {
190      mem_stream = stream_open_mem(NULL, 0);
191      if (!mem_stream)
192      {
193         err = IMGTOOLERR_OUTOFMEMORY;
194         goto done;
195      }
196
197      stream_seek(sourcef, pos, SEEK_SET);
198      len = stream_transfer(mem_stream, sourcef, fork_len);
199      if (len < fork_len)
200         stream_fill(mem_stream, 0, fork_len);
201
202      stream_seek(mem_stream, 0, SEEK_SET);
203      err = imgtool_partition_write_file(partition, filename, fork, mem_stream, opts, NULL);
204      if (err)
205         goto done;
206   }
207
208done:
209   if (mem_stream)
210      stream_close(mem_stream);
211   return err;
212}
213
214
215
216static imgtoolerr_t macbinary_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
217{
218   static const UINT32 attrs[] =
219   {
220      IMGTOOLATTR_TIME_CREATED,
221      IMGTOOLATTR_TIME_LASTMODIFIED,
222      IMGTOOLATTR_INT_MAC_TYPE,
223      IMGTOOLATTR_INT_MAC_CREATOR,
224      IMGTOOLATTR_INT_MAC_FINDERFLAGS,
225      IMGTOOLATTR_INT_MAC_COORDX,
226      IMGTOOLATTR_INT_MAC_COORDY,
227      IMGTOOLATTR_INT_MAC_FINDERFOLDER,
228      IMGTOOLATTR_INT_MAC_SCRIPTCODE,
229      IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS,
230      0
231   };
232   imgtoolerr_t err;
233   imgtool_image *image = imgtool_partition_image(partition);
234   UINT8 header[128];
235   UINT32 datafork_size;
236   UINT32 resourcefork_size;
237   UINT64 total_size;
238   UINT32 creation_time;
239   UINT32 lastmodified_time;
240   int version;
241   imgtool_attribute attr_values[10];
242
243   UINT32 type_code;
244   UINT32 creator_code;
245   UINT16 finder_flags;
246   UINT16 coord_x;
247   UINT16 coord_y;
248   UINT16 finder_folder;
249   UINT8 script_code = 0;
250   UINT8 extended_flags = 0;
251
252   /* read in the header */
253   memset(header, 0, sizeof(header));
254   stream_read(sourcef, header, sizeof(header));
255
256   /* check magic and zero fill bytes */
257   if (header[0] != 0x00)
258      return IMGTOOLERR_CORRUPTFILE;
259   if (header[74] != 0x00)
260      return IMGTOOLERR_CORRUPTFILE;
261   if (header[82] != 0x00)
262      return IMGTOOLERR_CORRUPTFILE;
263
264   datafork_size = pick_integer_be(header, 83, 4);
265   resourcefork_size = pick_integer_be(header, 87, 4);
266   total_size = stream_size(sourcef);
267
268   /* size of a MacBinary header is always 128 bytes */
269   if (total_size - pad128(datafork_size) - pad128(resourcefork_size) != 128)
270      return IMGTOOLERR_CORRUPTFILE;
271
272   /* check filename length byte */
273   if ((header[1] <= 0x00) || (header[1] > 0x3F))
274      return IMGTOOLERR_CORRUPTFILE;
275
276   /* check the CRC */
277   if (pick_integer_be(header, 124, 2) != ccitt_crc16(0, header, 124))
278   {
279      /* the CRC does not match; this file is MacBinary I */
280      version = 1;
281   }
282   else if (pick_integer_be(header, 102, 4) != 0x6D42494E)
283   {
284      /* did not see 'mBIN'; this file is MacBinary II */
285      if (header[122] < 0x81)
286         return IMGTOOLERR_CORRUPTFILE;
287      if (header[123] < 0x81)
288         return IMGTOOLERR_CORRUPTFILE;
289      version = 2;
290   }
291   else
292   {
293      /* we did see 'mBIN'; this file is MacBinary III */
294      if (header[122] < 0x82)
295         return IMGTOOLERR_CORRUPTFILE;
296      if (header[123] < 0x81)
297         return IMGTOOLERR_CORRUPTFILE;
298      version = 3;
299   }
300
301   type_code         = pick_integer_be(header, 65, 4);
302   creator_code      = pick_integer_be(header, 69, 4);
303   finder_flags      = pick_integer_be(header, 73, 1) << 8;
304   coord_x           = pick_integer_be(header, 75, 2);
305   coord_y           = pick_integer_be(header, 77, 2);
306   finder_folder     = pick_integer_be(header, 79, 2);
307   creation_time     = pick_integer_be(header, 91, 4);
308   lastmodified_time = pick_integer_be(header, 95, 4);
309
310   if (image)
311   {
312      /* write out both forks */
313      err = write_fork(partition, filename, "", sourcef, sizeof(header), datafork_size, opts);
314      if (err)
315         return err;
316      err = write_fork(partition, filename, "RESOURCE_FORK", sourcef, sizeof(header) + pad128(datafork_size), resourcefork_size, opts);
317      if (err)
318         return err;
319
320      /* set up attributes */
321      attr_values[0].t = mac_crack_time(creation_time);
322      attr_values[1].t = mac_crack_time(lastmodified_time);
323      attr_values[2].i = type_code;
324      attr_values[3].i = creator_code;
325      attr_values[4].i = finder_flags;
326      attr_values[5].i = coord_x;
327      attr_values[6].i = coord_y;
328      attr_values[7].i = finder_folder;
329      attr_values[8].i = script_code;
330      attr_values[9].i = extended_flags;
331
332      err = imgtool_partition_put_file_attributes(partition, filename, attrs, attr_values);
333      if (err)
334         return err;
335   }
336
337   return IMGTOOLERR_SUCCESS;
338}
339
340
341
342static imgtoolerr_t macbinary_checkstream(imgtool_stream *stream, imgtool_suggestion_viability_t *viability)
343{
344   imgtoolerr_t err;
345
346   err = macbinary_writefile(NULL, NULL, NULL, stream, NULL);
347   if (err == IMGTOOLERR_CORRUPTFILE)
348   {
349      /* the filter returned corrupt; this is not a valid file */
350      *viability = SUGGESTION_END;
351      err = IMGTOOLERR_SUCCESS;
352   }
353   else if (err == IMGTOOLERR_SUCCESS)
354   {
355      /* success; lets recommend this filter */
356      *viability = SUGGESTION_RECOMMENDED;
357   }
358   return err;
359}
360
361
362
363void filter_macbinary_getinfo(UINT32 state, union filterinfo *info)
364{
365   switch(state)
366   {
367      case FILTINFO_STR_NAME:         info->s = "macbinary"; break;
368      case FILTINFO_STR_HUMANNAME:   info->s = "MacBinary"; break;
369      case FILTINFO_STR_EXTENSION:   info->s = "bin"; break;
370      case FILTINFO_PTR_READFILE:      info->read_file = macbinary_readfile; break;
371      case FILTINFO_PTR_WRITEFILE:   info->write_file = macbinary_writefile; break;
372      case FILTINFO_PTR_CHECKSTREAM:   info->check_stream = macbinary_checkstream; break;
373   }
374}
src/mess/tools/imgtool/ti85.c
r1339r1340
1#include "osdepend.h"
2#include "imgtoolx.h"
3#include "utils.h"
4#include "formats/ti85_ser.h"
5
6static const char *var_type[] = {
7      "Real number",         //0x00
8      "Complex number",      //0x01
9      "Real vector",         //0x02
10      "Complex vector",      //0x03
11      "Real list",         //0x04
12      "Complex list",         //0x05
13      "Real matrix",         //0x06
14      "Complex matrix",      //0x07
15      "Real constatnt",      //0x08
16      "Complex constant",      //0x09
17      "Equation",         //0x0a
18      "Range settings",      //0x0b
19      "String",         //0x0c
20      "Graphics database",      //0x0d
21      "Graphics database",      //0x0e
22      "Graphics database",      //0x0f
23      "Graphics database",      //0x10
24      "Picture",         //0x11
25      "Program",         //0x12
26      "Range settings",      //0x13
27      "Unknown",         //0x14
28      "Range settings",      //0x15
29      "Range settings",      //0x16
30      "Range settings",      //0x17
31      "Range settings",      //0x18
32      "Range settings",      //0x19
33      "Range settings",      //0x1a
34      "Range settings"};      //0x1b
35
36typedef struct {
37   char signature[0x08];
38   unsigned char marker[0x03];
39   char comment[0x2a];
40   unsigned char data_size[0x02];
41} ti85_header;
42
43typedef struct {
44   imgtool_image base;
45   imgtool_stream *file_handle;
46   unsigned int size;
47   int modified;
48   UINT8 *data;
49   ti85_entry * entries;
50   int number_of_entries;
51} ti85_file;
52
53typedef struct {
54   imgtool_image base;
55   imgtool_stream *file_handle;
56   unsigned int size;
57   int modified;
58   UINT8 *data;
59} ti85b_file;
60
61typedef struct {
62   imgtool_directory base;
63   ti85_file *image;
64   int index;
65} ti85_iterator;
66
67typedef struct {
68   imgtool_directory base;
69   ti85b_file *image;
70   int index;
71} ti85b_iterator;
72
73#define HEADER(file) ((ti85_header*)file->data)
74
75static struct OptionTemplate ti85_fileoptions[] =
76{
77   { "ftype", "File type", IMGOPTION_FLAG_TYPE_INTEGER | IMGOPTION_FLAG_HASDEFAULT,0,27,"12"},
78   { NULL, 0, 0, 0, 0 }
79};
80
81static struct OptionTemplate ti85_createoptions[] =
82{
83   { "comment", "Comment", IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,0,0,"TI-85 file created with ImgTool"},
84   { NULL, NULL, 0, 0, 0, 0 }
85};
86
87#define TI85_OPTION_FTYPE   0
88#define TI85_OPTION_COMMENT   0
89
90static void ti85_file_info(imgtool_image *img, char *string, const int len);
91static int ti85_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
92static void ti85_file_exit(imgtool_image *img);
93static int ti85_file_beginenum(imgtool_image *img, imgtool_directory **outenum);
94static int ti85_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
95static void ti85_file_closeenum(imgtool_directory *enumeration);
96static int ti85_file_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
97static int ti85_file_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
98static int ti85_file_deletefile(imgtool_image *img, const char *fname);
99static int ti85_file_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
100
101static void ti85b_file_info(imgtool_image *img, char *string, const int len);
102static int ti85b_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
103static void ti85b_file_exit(imgtool_image *img);
104static int ti85b_file_beginenum(imgtool_image *img, imgtool_directory **outenum);
105static int ti85b_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
106static void ti85b_file_closeenum(imgtool_directory *enumeration);
107
108
109#define TI85FILE(name,human_name,extension) \
110IMAGEMODULE(         \
111   name,         \
112   human_name,      \
113   extension,      \
114   NULL,         \
115   NULL,         \
116   NULL,         \
117   0,         \
118   ti85_file_init,      \
119   ti85_file_exit,      \
120   ti85_file_info,      \
121   ti85_file_beginenum,   \
122   ti85_file_nextenum,   \
123   ti85_file_closeenum,   \
124   NULL,         \
125   ti85_file_readfile,   \
126   ti85_file_writefile,   \
127   ti85_file_deletefile,   \
128   ti85_file_create,   \
129   NULL,         \
130   NULL,         \
131   ti85_fileoptions,   \
132   ti85_createoptions   \
133)
134
135TI85FILE (ti85p, "TI-85 program file", "85p")
136TI85FILE (ti85s, "TI-85 string file (also ZShell programs)", "85s")
137TI85FILE (ti85i, "TI-85 picture file (85-image)", "85i")
138TI85FILE (ti85n, "TI-85 real number file", "85n")
139TI85FILE (ti85c, "TI-85 complex number file", "85c")
140TI85FILE (ti85l, "TI-85 list (real or complex) file", "85l")
141TI85FILE (ti85k, "TI-85 constant file", "85k")
142TI85FILE (ti85m, "TI-85 matrix (real or complex) file", "85m")
143TI85FILE (ti85v, "TI-85 vector (real or complex) file", "85v")
144TI85FILE (ti85d, "TI-85 graphics database file", "85d")
145TI85FILE (ti85e, "TI-85 equation file", "85e")
146TI85FILE (ti85r, "TI-85 range settings file", "85r")
147TI85FILE (ti85g, "TI-85 grouped file", "85g")
148TI85FILE (ti85, "TI-85 file", "85?")
149TI85FILE (ti86p, "TI-86 program file", "86p")
150TI85FILE (ti86s, "TI-86 string file (also ZShell programs)", "86s")
151TI85FILE (ti86i, "TI-86 picture file (85-image)", "86i")
152TI85FILE (ti86n, "TI-86 real number file", "86n")
153TI85FILE (ti86c, "TI-86 complex number file", "86c")
154TI85FILE (ti86l, "TI-86 list (real or complex) file", "86l")
155TI85FILE (ti86k, "TI-86 constant file", "86k")
156TI85FILE (ti86m, "TI-86 matrix (real or complex) file", "86m")
157TI85FILE (ti86v, "TI-86 vector (real or complex) file", "86v")
158TI85FILE (ti86d, "TI-86 graphics database file", "86d")
159TI85FILE (ti86e, "TI-86 equation file", "86e")
160TI85FILE (ti86r, "TI-86 range settings file", "86r")
161TI85FILE (ti86g, "TI-86 grouped file", "86g")
162TI85FILE (ti86, "TI-86 file", "86?")
163
164
165IMAGEMODULE(
166   ti85b,
167   "TI-85 memory backup file",
168   "85b",
169   NULL,
170   NULL,
171   NULL,
172   0,
173   ti85b_file_init,
174   ti85b_file_exit,
175   ti85b_file_info,
176   ti85b_file_beginenum,
177   ti85b_file_nextenum,
178   ti85b_file_closeenum,
179   NULL,
180   NULL,
181   NULL,
182   NULL,
183   NULL,
184   NULL,
185   NULL,
186   NULL,
187   NULL
188)
189
190static int ti85_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
191{
192   ti85_file *file;
193
194   file=*(ti85_file**)outimg=(ti85_file *) malloc(sizeof(ti85_file));
195   if (!file) return IMGTOOLERR_OUTOFMEMORY;
196
197   file->base.module = mod;
198   file->size=stream_size(f);
199   file->file_handle=f;
200
201   file->data = (unsigned char *) malloc(file->size);
202   if (!file->data) return IMGTOOLERR_OUTOFMEMORY;
203
204   if (stream_read(f, file->data, file->size)!=file->size)
205   {
206      free(file);
207      *outimg=NULL;
208      return IMGTOOLERR_READERROR;
209   }
210
211   if ( strncmp((char *) file->data, (char *) ti85_file_signature, 11) &&
212             strncmp((char *) file->data, (char *) ti86_file_signature, 11) )
213   {
214      free(file);
215      return IMGTOOLERR_CORRUPTIMAGE;
216   }
217
218
219   if (file->data[0x3b]==0x1d)
220   {
221      free(file);
222      return IMGTOOLERR_CORRUPTIMAGE;
223   }
224
225   file->number_of_entries = ti85_variables_count(file->data, file->size);
226
227
228   file->entries = (ti85_entry*) malloc (file->number_of_entries*sizeof(ti85_entry));
229   if (!file->entries) return IMGTOOLERR_OUTOFMEMORY;
230
231
232   ti85_variables_read(file->data, file->size, file->entries);
233
234   return 0;
235}
236
237static void ti85_file_exit(imgtool_image * img)
238{
239   ti85_file *file=(ti85_file*)img;
240   if (file->modified) {
241      stream_clear(file->file_handle);
242      stream_write(file->file_handle, file->data, file->size);
243   }
244   stream_close(file->file_handle);
245   free(file->entries);
246   free(file->data);
247   free(file);
248}
249
250static void ti85_file_info(imgtool_image *img, char *string, const int len)
251{
252   UINT16 file_checksum;
253   UINT16 checksum;
254   unsigned int data_size;
255
256   ti85_file *file=(ti85_file*)img;
257   char comment_with_null[0x2a+1]={ 0 };
258
259   strncpy(comment_with_null, HEADER(file)->comment, 0x2a);
260
261   data_size = HEADER(file)->data_size[1]*256 + HEADER(file)->data_size[0];
262   file_checksum = file->data[file->size-1]*256+file->data[file->size-2];
263   checksum = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE);
264
265   sprintf(string,"\nComment   : %s\nData size : %04xh\nEntries   : %d\nChecksum  : %04xh",
266         comment_with_null,
267         data_size,
268         file->number_of_entries,
269         file_checksum);
270   if (checksum!=file_checksum) strcat (string, " (BAD)");
271}
272
273static int ti85_file_beginenum(imgtool_image *img, imgtool_directory **outenum)
274{
275   ti85_file *file=(ti85_file*)img;
276   ti85_iterator *iter;
277
278   iter=*(ti85_iterator**)outenum = (ti85_iterator *) malloc(sizeof(ti85_iterator));
279   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
280
281   iter->base.module = img->module;
282
283   iter->image=file;
284   iter->index = 0;
285   return 0;
286}
287
288static int ti85_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
289{
290   ti85_iterator *iter=(ti85_iterator*)enumeration;
291
292   ent->eof=iter->index>=iter->image->number_of_entries;
293   if (!ent->eof)
294   {
295      memset(ent->fname,0,iter->image->entries[iter->index].name_size+1);
296      strncpy (ent->fname,
297          (char*)iter->image->data+iter->image->entries[iter->index].offset+0x06,
298          iter->image->entries[iter->index].name_size);
299      if (ent->attr)
300         sprintf(ent->attr,"%s (%02xh)",
301            var_type[iter->image->entries[iter->index].type],
302            iter->image->entries[iter->index].type);
303      ent->filesize = iter->image->entries[iter->index].data_size;
304      ent->corrupt=0;
305      iter->index++;
306   }
307
308   return 0;
309}
310
311static void ti85_file_closeenum(imgtool_directory *enumeration)
312{
313   free(enumeration);
314}
315
316static int ti85_findfile (ti85_file * file, const char * fname)
317{
318   int i;
319
320   for (i = 0; i < file->number_of_entries; i++)
321      if (!strnicmp(fname, (char *) file->data+file->entries[i].offset+0x06, file->entries[i].name_size) )
322         return i;     
323
324   return -1;
325}
326
327
328static int ti85_file_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
329{
330   ti85_file *file=(ti85_file*)img;
331   int start, size;
332   int ind;
333
334   if ((ind=ti85_findfile(file, fname))==-1) return IMGTOOLERR_MODULENOTFOUND;
335
336   size = file->entries[ind].data_size;
337   start = file->entries[ind].offset+file->entries[ind].head_size+0x04;
338
339   if (stream_write(destf, file->data+start, size) != size)
340              return IMGTOOLERR_WRITEERROR;
341   return 0;
342}
343
344static int ti85_file_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_)
345{
346   ti85_file *file=(ti85_file*)img;
347   int ind;
348
349   unsigned char name_size = strlen (fname);
350   UINT16 head_size = 0x04 + name_size;
351   UINT16 data_size = stream_size(sourcef);
352   unsigned char type = options_[TI85_OPTION_FTYPE].i;
353   unsigned int offset = file->size-2;
354
355   if (!(file->data=realloc(file->data, file->size+data_size+head_size+4)) )
356      return IMGTOOLERR_OUTOFMEMORY;
357
358   file->size+=data_size+head_size+4;
359
360   if (!(file->entries=realloc(file->entries, sizeof(ti85_entry)*(file->number_of_entries+1))) )
361      return IMGTOOLERR_OUTOFMEMORY;
362   file->number_of_entries++;
363
364   ind = file->number_of_entries-1;
365
366   file->entries[ind].head_size = head_size;
367   file->entries[ind].data_size = data_size;
368   file->entries[ind].type = type;
369   file->entries[ind].name_size = name_size;
370   file->entries[ind].offset = offset;
371
372   HEADER(file)->data_size[0] = (file->size-0x36)&0x00ff;
373   HEADER(file)->data_size[1] = ((file->size-0x36)&0xff00)>>8;
374
375   file->data[offset] = head_size&0x00ff;
376   file->data[offset+0x01] = (head_size&0xff00)>>8;
377   file->data[offset+0x02] = data_size&0x00ff;
378   file->data[offset+0x03] = (data_size&0xff00)>>8;
379   file->data[offset+0x04] = type;
380   file->data[offset+0x05] = name_size;
381
382   strncpy ((char*) file->data+offset+0x06, fname, name_size);
383
384   file->data[offset+head_size+0x02] = data_size%0x00ff;
385   file->data[offset+head_size+0x03] = (data_size%0xff00)>>8;
386
387   if (stream_read(sourcef, file->data+offset+head_size+0x04, data_size)!=data_size)
388      return IMGTOOLERR_READERROR;
389   
390   file->data[file->size-2] = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0x00ff;
391   file->data[file->size-1] = (ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0xff00)>>8;
392
393   file->modified=1;
394
395   return 0;
396}
397
398static int ti85_file_deletefile(imgtool_image *img, const char *fname)
399{
400   ti85_file *file=(ti85_file*)img;
401   int ind,i;
402   int size, start;
403
404   if ((ind=ti85_findfile(file, fname))==-1 )
405      return IMGTOOLERR_MODULENOTFOUND;
406
407   size = file->entries[ind].data_size+file->entries[ind].head_size+0x04;
408   start = file->entries[ind].offset;
409
410   memmove(file->data+start, file->data+start+size, file->size-start-size);
411   memmove(file->entries+ind*sizeof(ti85_entry),
412      file->entries+(ind+1)*sizeof(ti85_entry),
413      (file->number_of_entries-ind)*sizeof(ti85_entry));
414
415   for (i = ind; i < file->number_of_entries; i++)
416      file->entries[i].offset-=size;
417
418   file->size-=size;
419   file->data[file->size-2] = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0x00ff;
420   file->data[file->size-1] = (ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0xff00)>>8;
421   file->modified=1;
422
423   return 0;
424}
425
426static int ti85_file_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
427{
428
429   ti85_header header = {   {'*','*','T','I','8','5','*','*'},
430            {0x1a, 0x0c, 0x00},
431            "",
432            {0x00, 0x00} };
433
434   char checksum[] = {0x00, 0x00};
435
436   strncpy(header.comment, options_[TI85_OPTION_COMMENT].s,0x2a);
437   if (stream_write(f, &header, sizeof(ti85_header)) != sizeof(ti85_header))
438      return  IMGTOOLERR_WRITEERROR;
439   if (stream_write(f, &checksum, 2) != 2)
440      return  IMGTOOLERR_WRITEERROR;
441
442   return 0;
443}
444
445static int ti85b_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
446{
447   ti85b_file *file;
448
449   file=*(ti85b_file**)outimg=(ti85b_file *) malloc(sizeof(ti85b_file));
450   if (!file) return IMGTOOLERR_OUTOFMEMORY;
451
452   file->base.module = mod;
453   file->size=stream_size(f);
454   file->file_handle=f;
455
456   file->data = (unsigned char *) malloc(file->size);
457   if (!file->data) return IMGTOOLERR_OUTOFMEMORY;
458
459   if (stream_read(f, file->data, file->size)!=file->size)
460   {
461      free(file);
462      *outimg=NULL;
463      return IMGTOOLERR_READERROR;
464   }
465
466   if ( strncmp((char *) file->data, (char *) ti85_file_signature, 11))
467   {
468      free(file);
469      return IMGTOOLERR_CORRUPTIMAGE;
470   }
471
472   if (file->data[0x3b]!=0x1d)
473   {
474      free(file);
475      return IMGTOOLERR_CORRUPTIMAGE;
476   }
477
478   return 0;
479}
480
481static void ti85b_file_exit(imgtool_image * img)
482{
483   ti85b_file *file=(ti85b_file*)img;
484   stream_close(file->file_handle);
485   free(file->data);
486   free(file);
487}
488
489static void ti85b_file_info(imgtool_image *img, char *string, const int len)
490{
491   UINT16 file_checksum;
492   UINT16 checksum;
493   unsigned int data_size;
494
495   ti85b_file *file=(ti85b_file*)img;
496   char comment_with_null[0x2a+1]={ 0 };
497
498   strncpy(comment_with_null, HEADER(file)->comment, 0x2a);
499
500   data_size = HEADER(file)->data_size[1]*256 + HEADER(file)->data_size[0] - 17;
501   file_checksum = file->data[file->size-1]*256+file->data[file->size-2];
502   checksum = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE);
503
504   sprintf(string,"\nComment   : %s\nData size : %04xh\nChecksum  : %04xh",
505         comment_with_null,
506         data_size,
507         file_checksum);
508   if (checksum!=file_checksum) strcat (string, " (BAD)");
509}
510
511static int ti85b_file_beginenum(imgtool_image *img, imgtool_directory **outenum)
512{
513   ti85b_file *file=(ti85b_file*)img;
514   ti85b_iterator *iter;
515
516   iter=*(ti85b_iterator**)outenum = (ti85b_iterator *) malloc(sizeof(ti85b_iterator));
517   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
518
519   iter->base.module = img->module;
520
521   iter->image=file;
522   iter->index = 0;
523   return 0;
524}
525
526static int ti85b_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
527{
528   ti85b_iterator *iter=(ti85b_iterator*)enumeration;
529
530   ent->eof=iter->index>=3;
531   if (!ent->eof)
532   {
533      switch (iter->index) {
534         case 0 :
535            strcpy (ent->fname, "TI-85 Memory");
536            ent->filesize = iter->image->data[0x3a]*256 +iter->image->data[0x39];
537            break;
538         case 1 :
539            strcpy (ent->fname, "User Memory");
540            ent->filesize = iter->image->data[0x3d]*256 +iter->image->data[0x3c];
541            break;
542         case 2 :
543            strcpy (ent->fname, "VAT");
544            ent->filesize = iter->image->data[0x3f]*256 +iter->image->data[0x3e];
545            break;
546      }
547
548     
549      ent->corrupt=0;
550      iter->index++;
551   }
552
553   return 0;
554}
555
556static void ti85b_file_closeenum(imgtool_directory *enumeration)
557{
558   free(enumeration);
559}
src/mess/tools/imgtool/lynx.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6
7/* commodore 64 lynx format
8   motivation
9   stuff several files in one file, for archiving and transmission?
10   no packing?
11
12   commodore basic header
13   ended with 0 0 0 0x0d
14   string count begin of data in 254 byte blocks 0x0d
15
16   string count of entries in directory 0x0d
17
18   count of entries
19    name 0x13
20   string blocks 0x13
21   char type 0x13
22   string bytes_in_last_block 0x13
23
24   data for the entries
25    filled up to 254 byte blocks
26
27*/
28
29typedef struct {
30   char name[21];
31   int offset, size;
32   char filetype;
33} LYNX_ENTRY;
34
35typedef struct {
36   imgtool_image base;
37   imgtool_stream *file_handle;
38   int size;
39   unsigned char *data;
40   int count;
41   LYNX_ENTRY *entries;
42} lynx_image;
43
44typedef struct {
45   imgtool_directory base;
46   lynx_image *image;
47   int index;
48} lynx_iterator;
49
50static int lynx_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
51static void lynx_image_exit(imgtool_image *img);
52//static void lynx_image_info(imgtool_image *img, char *string, const int len);
53static int lynx_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
54static int lynx_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
55static void lynx_image_closeenum(imgtool_directory *enumeration);
56static int lynx_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
57
58IMAGEMODULE(
59   lynx,
60   "Commodore 64 Archive",   /* human readable name */
61   "lnx",                        /* file extension */
62   NULL,                        /* crcfile */
63   NULL,                        /* crc system name */
64   NULL,                        /* eoln */
65   0,                           /* flags */
66   lynx_image_init,            /* init function */
67   lynx_image_exit,            /* exit function */
68   NULL,//lynx_image_info,      /* info function */
69   lynx_image_beginenum,         /* begin enumeration */
70   lynx_image_nextenum,         /* enumerate next */
71   lynx_image_closeenum,         /* close enumeration */
72   NULL,/* free space on image */
73   lynx_image_readfile,         /* read file */
74   NULL,/* write file */
75   NULL,/* delete file */
76   NULL,/* create image */
77   NULL,                        /* read sector */
78   NULL,                        /* write sector */
79   NULL,                        /* file options */
80   NULL                        /* create options */
81)
82
83static int lynx_read_line(lynx_image *image, int pos)
84{
85   int i;
86   for (i=0; (pos+i<image->size)&&(image->data[pos+i]!=0xd); i++ ) ;
87   if (pos+i<image->size) i++;
88   return i;
89}
90
91static int lynx_read_image(lynx_image *image)
92{
93   int i=0, j, n;
94
95   n=lynx_read_line(image, i);
96   if ( n==0 ) return IMGTOOLERR_CORRUPTIMAGE;
97   i+=n;
98
99   n=lynx_read_line(image, i);
100   j=atoi((char *)image->data+i); /* begin of data */
101   if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
102   i+=n;
103
104   n=lynx_read_line(image, i);
105   image->count=atoi((char *)image->data+i);
106   if ((n==0)||(image->count==0)) return IMGTOOLERR_CORRUPTIMAGE;
107   i+=n;
108
109   image->entries=malloc(sizeof(LYNX_ENTRY)*image->count);
110   if (!image->entries) return IMGTOOLERR_OUTOFMEMORY;
111
112   image->entries[0].offset=j*254;
113
114   for (j=0; j<image->count; j++) {
115      int a,b;
116
117      n=lynx_read_line(image, i);
118      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
119      strncpy(image->entries[j].name,(char *)image->data+i, n-1);
120      i+=n;
121
122      n=lynx_read_line(image, i);
123      a=atoi((char *)image->data+i);
124      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
125      i+=n;
126
127      n=lynx_read_line(image, i);
128      image->entries[j].filetype=image->data[i];
129      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
130      i+=n;
131
132      n=lynx_read_line(image, i);
133      b=atoi((char *)image->data+i);
134      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
135      i+=n;
136
137      image->entries[j].size=(a-1)*254+b-1;
138      if (j+1<image->count)
139         image->entries[j+1].offset=image->entries[j].offset+254*a;
140   }
141
142   return 0;
143}
144
145static int lynx_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
146{
147   lynx_image *image;
148   int rc;
149
150   image=*(lynx_image**)outimg=(lynx_image *) malloc(sizeof(lynx_image));
151   if (!image) return IMGTOOLERR_OUTOFMEMORY;
152
153   memset(image, 0, sizeof(lynx_image));
154   image->base.module = mod;
155   image->size=stream_size(f);
156   image->file_handle=f;
157
158   image->data = (unsigned char *) malloc(image->size);
159   if ( (!image->data)
160       ||(stream_read(f, image->data, image->size)!=image->size) ) {
161      free(image);
162      *outimg=NULL;
163      return IMGTOOLERR_OUTOFMEMORY;
164   }
165   if ( (rc=lynx_read_image(image)) ) {
166      if (image->entries) free(image->entries);
167      free(image);
168      *outimg=NULL;
169      return rc;
170   }
171
172   return 0;
173}
174
175static void lynx_image_exit(imgtool_image *img)
176{
177   lynx_image *image=(lynx_image*)img;
178   stream_close(image->file_handle);
179   free(image->entries);
180   free(image->data);
181   free(image);
182}
183
184#if 0
185static void lynx_image_info(imgtool_image *img, char *string, const int len)
186{
187   lynx_image *image=(lynx_image*)img;
188   char dostext_with_null[33]= { 0 };
189   char name_with_null[25]={ 0 };
190   strncpy(dostext_with_null, HEADER(image)->dostext, 32);
191   strncpy(name_with_null, HEADER(image)->description, 24);
192   sprintf(string,"%s\n%s\nversion:%.4x max entries:%d",
193         dostext_with_null,
194         name_with_null,
195         GET_UWORD(HEADER(image)->version),
196         HEADER(image)->max_entries);
197}
198#endif
199
200static int lynx_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
201{
202   lynx_image *image=(lynx_image*)img;
203   lynx_iterator *iter;
204
205   iter=*(lynx_iterator**)outenum = (lynx_iterator *) malloc(sizeof(lynx_iterator));
206   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
207
208   iter->base.module = img->module;
209
210   iter->image=image;
211   iter->index = 0;
212   return 0;
213}
214
215static int lynx_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
216{
217   lynx_iterator *iter=(lynx_iterator*)enumeration;
218   ent->corrupt=0;
219   
220   ent->eof=iter->index>=iter->image->count;
221   if (!ent->eof) {
222      strcpy(ent->fname, iter->image->entries[iter->index].name);
223      if (ent->attr) {
224         switch (iter->image->entries[iter->index].filetype) {
225         case 'P': strcpy(ent->attr,"PRG");break;
226         case 'S': strcpy(ent->attr,"SEQ");break;
227         case 'R': strcpy(ent->attr,"REL");break;
228         case 'U': strcpy(ent->attr,"USR");break;
229         default:
230            sprintf(ent->attr,"type:%c",
231                  iter->image->entries[iter->index].filetype );
232         }
233      }
234      ent->filesize=iter->image->entries[iter->index].size;
235      iter->index++;
236   }
237   return 0;
238}
239
240static void lynx_image_closeenum(imgtool_directory *enumeration)
241{
242   free(enumeration);
243}
244
245static LYNX_ENTRY* lynx_image_findfile(lynx_image *image, const char *fname)
246{
247   int i;
248
249   for (i=0; i<image->count; i++) {
250      if (!mame_stricmp(fname, image->entries[i].name) ) return image->entries+i;
251   }
252   return NULL;
253}
254
255static int lynx_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
256{
257   lynx_image *image=(lynx_image*)img;
258   LYNX_ENTRY *entry;
259
260   if ((entry=lynx_image_findfile(image, fname))==NULL ) return IMGTOOLERR_MODULENOTFOUND;
261
262   if (stream_write(destf, image->data+entry->offset, entry->size)!=entry->size) {
263      return IMGTOOLERR_WRITEERROR;
264   }
265
266   return 0;
267}
268
src/mess/tools/imgtool/nccard.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include <ctype.h>
5#include "osdepend.h"
6#include "imgtoolx.h"
7
8/* NC Card image handling code by Kevin Thacker. February 2001 */
9
10static int nc_card_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
11static void nc_card_image_exit(imgtool_image *img);
12static size_t nc_card_image_freespace(imgtool_image *img);
13static int nc_card_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
14static int nc_card_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
15static int nc_card_image_deletefile(imgtool_image *img, const char *fname);
16static int nc_card_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
17static int nc_card_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
18static int nc_card_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
19static void nc_card_image_closeenum(imgtool_directory *enumeration);
20
21IMAGEMODULE(
22   nccard,
23   "NC100/200 PCMCIA Ram Card Image",         /* human readable name */
24   "crd",                     /* file extension */
25   NULL,                     /* crcfile */
26   NULL,                     /* crc system name */
27   EOLN_CRLF,                  /* eoln */
28   IMGMODULE_FLAG_FILENAMES_PREFERUCASE,   /* flags */
29   nc_card_image_init,            /* init function */
30   nc_card_image_exit,            /* exit function */
31   NULL,                     /* info function */
32   nc_card_image_beginenum,      /* begin enumeration */
33   nc_card_image_nextenum,         /* enumerate next */
34   nc_card_image_closeenum,      /* close enumeration */
35   nc_card_image_freespace,      /* free space on image    */
36   nc_card_image_readfile,         /* read file */
37   nc_card_image_writefile,      /* write file */
38   nc_card_image_deletefile,      /* delete file */
39   nc_card_image_create,         /* create image */
40   NULL,
41   NULL,
42   NULL,                     /* file options */
43   NULL                     /* create options */
44)
45
46/*
47   NC PCMCIA RAM Card uses a FAT-like filesystem
48
49   Blocks are fixed at 256 bytes in size.
50   
51   Block 0 and Block 1 are reserved for a boot program.
52
53   Block 2 is reserved for root directory.
54
55   Block 3..(3+num_fat_blocks-1) are reserved for fat table.
56
57   Block (3+num_fat_blocks).. are used for data storage.
58
59   The FAT table uses two bytes for each entry.
60
61   The blocks used by a file are stored in the table in a link-list
62   structure.
63
64   The index of the first block is stored in the directory entry.
65   This entry is looked up in the FAT table. If the entry contains
66   another number (other than 0x0ffff and 0x0fffe), this is the next
67   block used by the file. If the number is 0x0ffff this means this
68   block is the last used by the file.
69   
70   0x0fffe indicates a reserved block.
71
72   The maximum supported PCMCIA Ram card size is 1mb, and there are
73   4096 256-byte blocks on each card. Therefore a FAT entry uses 12-bits
74   to store the block index, leaving the top 4-bits as a status??
75   
76   Maximum size of a file on the PCMCIA Ram card is 65536 bytes.
77*/
78struct nc_card_dir_entry
79{
80   /* filename, up to 12 chars, any unused chars are padded with zero's */
81   /* if first char is 0, this entry has been deleted */
82   unsigned char filename[12];
83   /* unused?? */
84   unsigned char unused[1];
85   /* 5 = basic, 0 = ascii text, 3=directory entry? */
86   unsigned char type;
87   /* size of file in bytes */
88   unsigned char size_low_byte;
89   unsigned char size_high_byte;
90   /* format unknown */
91   unsigned char packed_date[4];
92   /* 2-byte block index. first block used by file, other blocks
93   found in fat table */
94   unsigned char first_block_low;
95   unsigned char first_block_high;
96   /* unused?? */
97   unsigned char pad[32 - 22];
98};
99
100#define NC_FAT_END_OF_LIST   0x0ffff
101#define NC_FAT_RESERVED      0x0fffe
102
103struct nc_memcard
104{
105   unsigned char *memcard_data;
106   unsigned long memcard_size;
107   int fat_num_blocks;
108   int max_block_index;
109};
110
111/* each block is 256 bytes in size */
112#define NC_BLOCK_SIZE   256
113/* fat begins at block 3 */
114#define NC_FAT_BLOCK 3
115
116#define NC_DIR_ENTRY_TYPE_ASCII_FILE 0
117#define NC_DIR_ENTRY_TYPE_BASIC_FILE 5
118#define NC_DIR_ENTRY_TYPE_DIR 3
119
120
121static int   memcard_init(struct nc_memcard *memcard, int size)
122{
123   /* set size of memcard */
124   memcard->memcard_size = size;
125   /* allocate memory for it */
126   memcard->memcard_data = malloc(size);
127
128   if (memcard->memcard_data==0)
129      return 0;
130
131   /* calculate maximum number of blocks for fat to use */
132   memcard->max_block_index = (memcard->memcard_size + NC_BLOCK_SIZE-1)/NC_BLOCK_SIZE;
133
134   memcard->fat_num_blocks = ((memcard->max_block_index<<1) + NC_BLOCK_SIZE-1)/NC_BLOCK_SIZE;
135
136   return 1;
137}
138
139static void   memcard_free(struct nc_memcard *memcard)
140{
141   if (memcard->memcard_data!=NULL)
142   {
143      free(memcard->memcard_data);
144      memcard->memcard_data = NULL;
145   }
146}
147
148
149/* write to fat */
150static void   memcard_fat_write(struct nc_memcard *memcard,int index1, int data)
151{
152   unsigned long offset;
153
154   offset = (NC_FAT_BLOCK*NC_BLOCK_SIZE) + (index1<<1);
155
156   memcard->memcard_data[offset] = data & 0x0ff;
157   memcard->memcard_data[offset+1] = (data>>8);
158}
159
160/* read from fat */
161static int   memcard_fat_read(struct nc_memcard *memcard,int index1)
162{
163   int data;
164   unsigned long offset;
165
166   offset = (NC_FAT_BLOCK*NC_BLOCK_SIZE) + (index1<<1);
167
168   data = (memcard->memcard_data[offset] & 0x0ff) | ((memcard->memcard_data[offset+1] & 0x0ff)<<8);
169
170   return data;
171}
172
173/* get block index stored at the specified block index */
174static int memcard_fat_get_next_block(struct nc_memcard *memcard,int index1)
175{
176   return memcard_fat_read(memcard,index1);
177}
178
179/* get index of free block */
180static int   memcard_fat_get_free_block(struct nc_memcard *memcard)
181{
182   int i;
183
184   for (i=0; i<memcard->max_block_index; i++)
185   {
186      if (memcard_fat_read(memcard,i)==0)
187      {
188         return i;
189      }
190   }
191   return -1;
192}
193
194
195static unsigned long memcard_block_to_offset(int block)
196{
197   return block*NC_BLOCK_SIZE;
198}
199
200
201/* returns offset to directory entry */
202static unsigned long memcard_get_free_dir_entry(struct nc_memcard *memcard)
203{
204   /* offset within memcard data of this directory entry inside the parent */
205   int offset_in_parent_dir = NC_BLOCK_SIZE*2;
206   int previous_block;
207   int current_block = 2;
208   unsigned long offset;
209
210   while (current_block!=NC_FAT_END_OF_LIST)
211   {
212      int i;
213      offset = memcard_block_to_offset(current_block);
214
215      for (i=0; i<(NC_BLOCK_SIZE/32); i++)
216      {
217         if (memcard->memcard_data[offset]==0)
218         {
219            return offset;
220         }
221     
222         offset+=32;
223      }
224
225      previous_block = current_block;
226      current_block = memcard_fat_get_next_block(memcard,current_block);
227     
228      if (current_block!=NC_FAT_END_OF_LIST)
229      {
230         current_block &= 0x0fff;
231      }
232   }
233
234   /* out of entries within current blocks occupied by directory.
235   try to expand directory by one more block */
236
237   current_block = memcard_fat_get_free_block(memcard);
238
239   if (current_block!=-1)
240   {
241      int size;
242      unsigned long block_offset;
243      struct nc_card_dir_entry *dir_entry;
244
245      /* update size of directory */
246      dir_entry = (struct nc_card_dir_entry *)&memcard->memcard_data[offset_in_parent_dir];
247
248      /* get size of file from directory entry */
249      size = ((dir_entry->size_high_byte & 0x0ff)<<8) | (dir_entry->size_low_byte & 0x0ff);
250
251      size+=NC_BLOCK_SIZE;
252
253      /* set size of file in directory entry */
254      dir_entry->size_high_byte = (size>>8) & 0x0ff;
255      dir_entry->size_low_byte = size & 0x0ff;
256
257      /* got a new block */
258      block_offset = memcard_block_to_offset(current_block);
259
260      /* clear block */
261      /* only really necessary to clear first byte of each dir entry - but I'll clear
262      it all to give decent compressable cards */
263      memset(&memcard->memcard_data[block_offset], 0, NC_BLOCK_SIZE);
264
265      /* setup fat */
266      memcard_fat_write(memcard,previous_block, current_block|0x02000);
267      memcard_fat_write(memcard,current_block, NC_FAT_END_OF_LIST);
268
269      /* return first offset in new block */
270      return block_offset;
271   }
272
273   return -1;
274}
275
276const char *nc_memcard_executable_id = "NC100PRG";
277
278/* if memory card has "NC100PRG" at 0x0200 then the card is executable! */
279static int memcard_is_executable(struct nc_memcard *memcard)
280{
281   if (memcmp(&memcard->memcard_data[0x0200], nc_memcard_executable_id, 8)==0)
282   {
283      return 1;
284   }
285
286   return 0;
287}
288
289
290/* format a blank card */
291static void   memcard_format(struct nc_memcard *memcard)
292{
293   int i;
294
295   /* initialise all to zero */
296   /* real NC100 does not do this */
297   memset(memcard->memcard_data, 0, memcard->memcard_size);
298
299   /* not executable */
300   /* real NC100 does not do this */
301   memcard->memcard_data[0] = 0x0c9;
302
303   /* mark boot block as used */
304   memcard_fat_write(memcard,0, NC_FAT_END_OF_LIST);
305   memcard_fat_write(memcard,1, NC_FAT_END_OF_LIST);
306   /* mark directory block as used */
307   memcard_fat_write(memcard,2, NC_FAT_END_OF_LIST);
308
309   /* mark fat blocks as used */
310   for (i=0; i<memcard->fat_num_blocks; i++)
311   {
312      memcard_fat_write(memcard,3+i, NC_FAT_END_OF_LIST);
313   }
314
315   /* reserved at end of fat table - required?? */
316   memcard_fat_write(memcard,memcard->max_block_index-1, NC_FAT_RESERVED);
317
318   {
319      /* format for NC100 */
320      unsigned long dir_entry_offset = memcard_get_free_dir_entry(memcard);
321      int dir_size = NC_BLOCK_SIZE;
322      struct nc_card_dir_entry *dir_entry;
323
324      dir_entry = (struct nc_card_dir_entry *)&memcard->memcard_data[dir_entry_offset];
325
326      strcpy((char *)dir_entry->filename,(char *)"NC100");
327      dir_entry->size_high_byte = (dir_size>>8) & 0x0ff;
328      dir_entry->size_low_byte = (dir_size & 0x0ff);
329      dir_entry->first_block_high = 0x020;
330      dir_entry->first_block_low = 0x02;
331      dir_entry->type = NC_DIR_ENTRY_TYPE_DIR;
332   }
333}
334
335
336static unsigned long memcard_locate_dir_entry(struct nc_memcard *memcard,char *pNCFilename)
337{
338   int current_block = 2;
339   unsigned long offset;
340
341   while (current_block!=NC_FAT_END_OF_LIST)
342   {
343      int i;
344
345      offset = memcard_block_to_offset(current_block);
346
347      for (i=0; i<(NC_BLOCK_SIZE/32); i++)
348      {
349         if (memcard->memcard_data[offset]!=0)
350         {
351            if (memcmp(&memcard->memcard_data[offset], pNCFilename,12)==0)
352            {
353               return offset;
354            }
355         }
356     
357         offset+=32;
358      }
359
360      current_block = memcard_fat_get_next_block(memcard,current_block);
361     
362      if (current_block!=NC_FAT_END_OF_LIST)
363      {
364         current_block = current_block & 0x0fff;
365      }
366   }
367
368   return -1;
369}
370
371static int   memcard_del(struct nc_memcard *memcard,char *pNCFilename)
372{
373   unsigned long dir_entry_offset = memcard_locate_dir_entry(memcard,pNCFilename);
374   int success_code = 0;
375
376   if (dir_entry_offset!=-1)
377   {
378      int current_block;
379      struct nc_card_dir_entry *dir_entry;
380
381      dir_entry = (struct nc_card_dir_entry *)&memcard->memcard_data[dir_entry_offset];
382
383      /* get first block index from directory entry */
384      current_block = ((dir_entry->first_block_high & 0x0f)<<8) | dir_entry->first_block_low;
385
386      while (current_block!=0)
387      {
388         int next_block;
389     
390         /* get next block in list */
391         next_block = memcard_fat_get_next_block(memcard,current_block);
392         /* zero out this block */
393         memcard_fat_write(memcard,current_block,0);
394         
395         /* go to next block */
396         current_block = next_block;
397
398         if (current_block!=NC_FAT_END_OF_LIST)
399         {
400            current_block &= 0x0fff;
401         }
402      }
403
404      /* clear first char of filename */
405      dir_entry->filename[0] = '\0';
406      success_code = 1;
407   }
408
409   return success_code;
410}
411
412
413struct nc_card_image
414{
415   imgtool_image base;
416   imgtool_stream *file_handle;
417   struct nc_memcard memcard;
418};
419
420static int nc_card_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
421{
422   struct nc_card_image *nc_card;
423
424   *outimg = NULL;
425
426   nc_card = (struct nc_card_image *)malloc(sizeof(struct nc_card_image));
427
428   if (!nc_card)
429   {
430      return IMGTOOLERR_OUTOFMEMORY;
431   }
432
433   nc_card->file_handle = f;
434   nc_card->base.module = mod;
435
436   /* allocate a big chunk of memory for memcard data - max size will be 1mb! */
437   if (!memcard_init(&nc_card->memcard, stream_size(f)))
438   {
439      return IMGTOOLERR_OUTOFMEMORY;
440   }
441
442   /* read data into memcard */
443   if (stream_read(f, nc_card->memcard.memcard_data, nc_card->memcard.memcard_size)!=nc_card->memcard.memcard_size)
444   {
445      memcard_free(&nc_card->memcard);
446
447      return IMGTOOLERR_READERROR;
448   }
449
450   *outimg = (imgtool_image *)nc_card;
451   return 0;
452}
453
454static void nc_card_image_exit(imgtool_image *img)
455{
456   struct nc_card_image *nc_card = (struct nc_card_image *)img;
457
458   stream_seek(nc_card->file_handle, 0, SEEK_SET);
459   stream_write(nc_card->file_handle, nc_card->memcard.memcard_data, nc_card->memcard.memcard_size);
460   stream_close(nc_card->file_handle);
461
462   memcard_free(&nc_card->memcard);
463}
464
465
466/* count number of free blocks and calculate freespace */
467static size_t nc_card_image_freespace(imgtool_image *img)
468{
469   struct nc_card_image *nc_card = (struct nc_card_image *)img;
470   int i;
471   int count;
472
473   count = 0;
474   for (i=0; i<nc_card->memcard.max_block_index; i++)
475   {
476      if (memcard_fat_read(&nc_card->memcard,i)==0)
477      {
478         count++;
479      }
480   }
481   return count*NC_BLOCK_SIZE;
482}
483
484/* create a empty image */
485/* in this case a formatted image */
486static int nc_card_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
487{
488   int code;
489
490   struct nc_memcard memcard;
491   
492   /* allocate a big chunk of memory for memcard data - max size will be 1mb! */
493   if (!memcard_init(&memcard, 1024*1024))
494   {
495      return IMGTOOLERR_OUTOFMEMORY;
496   }
497
498   /* format the card */
499   memcard_format(&memcard);
500
501   /* write out */
502   code = 0;
503   if (stream_write(f, memcard.memcard_data, memcard.memcard_size) != memcard.memcard_size)
504   {
505      /* write error! */
506      code = IMGTOOLERR_WRITEERROR;
507   }
508
509   /* free memcard data */
510   memcard_free(&memcard);
511
512   /* return success or failure code */
513   return code;
514}
515
516static void setup_nc_filename(char *nc_filename, const char *fname)
517{
518   char ch;
519   int offset;
520
521   memset(nc_filename, 0, 12);
522
523   offset = 0;
524   do
525   {
526      /* get char */
527      ch = fname[offset];
528
529      if (ch!=0)
530      {
531         /* convert to upper case */
532         ch = toupper(ch);
533         nc_filename[offset] = ch;
534         offset++;
535      }
536   }
537   while ((ch!=0) && (offset<12));
538}
539
540static int nc_card_image_deletefile(imgtool_image *img, const char *fname)
541{
542   struct nc_card_image *nc_card = (struct nc_card_image *)img;
543   char nc_filename[12];
544
545   setup_nc_filename(nc_filename,fname);
546
547   if (memcard_del(&nc_card->memcard,nc_filename))
548   {
549      return IMGTOOLERR_MODULENOTFOUND;     
550   }
551
552   return 0;
553}
554
555
556
557/* get a file from the memcard */
558static int nc_card_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
559{
560   struct nc_card_image *nc_card = (struct nc_card_image *)img;
561   char nc_filename[12];
562   unsigned long dir_entry_offset;
563   
564   setup_nc_filename(nc_filename, fname);
565
566   dir_entry_offset = memcard_locate_dir_entry(&nc_card->memcard,(char *)nc_filename);
567
568   if (dir_entry_offset!=-1)
569   {
570      struct nc_card_dir_entry *dir_entry;
571      int current_block;
572      int length_remaining;
573
574      dir_entry = (struct nc_card_dir_entry *)&nc_card->memcard.memcard_data[dir_entry_offset];
575
576      /* get size of file from directory entry */
577      length_remaining = ((dir_entry->size_high_byte & 0x0ff)<<8) | (dir_entry->size_low_byte & 0x0ff);
578   
579      /* get first block index from directory entry */
580      current_block = ((dir_entry->first_block_high & 0x0f)<<8) | dir_entry->first_block_low;
581
582      /* keep going until we have written all data or we have got to end of block list */
583      while ((length_remaining!=0) && (current_block!=NC_FAT_END_OF_LIST))
584      {
585         unsigned long block_offset;
586         int copy_length;
587
588         /* get offset of block data in memcard data */
589         block_offset = memcard_block_to_offset(current_block);
590     
591         /* calc amount of data to copy from block */
592         if (length_remaining<NC_BLOCK_SIZE)
593         {
594            copy_length = length_remaining;
595         }
596         else
597         {
598            copy_length = NC_BLOCK_SIZE;
599         }
600
601         /* output to file */
602         if (stream_write(destf, &nc_card->memcard.memcard_data[block_offset], copy_length)!=copy_length)
603            return IMGTOOLERR_WRITEERROR;
604     
605         /* update length of data remaining to write */
606         length_remaining -=copy_length;   
607
608         /* get next block in list */
609         current_block = memcard_fat_get_next_block(&nc_card->memcard,current_block);
610         
611         if (current_block!=NC_FAT_END_OF_LIST)
612         {
613            current_block &= 0x0fff;
614         }
615      }
616   }
617
618   return 0;
619}
620
621/* put a file to the memcard */
622static int nc_card_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_)
623{
624   struct nc_card_image *nc_card = (struct nc_card_image *)img;
625   unsigned long length;
626   unsigned long offset;
627
628   char nc_filename[12];
629
630   length = stream_size(sourcef);
631
632   /* locate a free directory entry */
633   offset = memcard_get_free_dir_entry(&nc_card->memcard);
634
635   setup_nc_filename(nc_filename, fname);
636
637   if (offset!=-1)
638   {
639      /* got a directory entry */
640
641      int   current_block;
642      int previous_block;
643      unsigned long block_offset;
644      unsigned long file_offset = 0;
645      unsigned long length_remaining = length;
646      struct nc_card_dir_entry *dir_entry;
647      int copy_length;
648
649      /* do not transfer more then 65536 bytes */
650      /* this is max size of file on card */
651      /* file size specified with 2 bytes only! */
652      if (length_remaining>65536)
653      {
654         length_remaining = 65536;
655      }
656
657      /* locate the first free block */
658      current_block = memcard_fat_get_free_block(&nc_card->memcard);
659
660      if (current_block!=-1)
661      {
662         /* initialise directory entry - blank all entries */
663         memset(&nc_card->memcard.memcard_data[offset], 0, 32);
664
665         dir_entry = (struct nc_card_dir_entry *)&nc_card->memcard.memcard_data[offset];
666         /* set size of file in directory entry */
667         dir_entry->size_high_byte = (length>>8) & 0x0ff;
668         dir_entry->size_low_byte = length & 0x0ff;
669         /* set first block in directory entry */
670         dir_entry->first_block_high = ((current_block>>8) & 0x0f) | 0x020;
671         dir_entry->first_block_low = (current_block & 0x0ff);
672         /* setup filename */
673         strncpy((char *)dir_entry->filename,(char *)nc_filename, 12);
674         
675         while (length_remaining!=0)
676         {
677            /* get offset of block data */
678            block_offset = memcard_block_to_offset(current_block);
679         
680            /* calc amount of data to copy to block */
681            if (length_remaining<NC_BLOCK_SIZE)
682            {
683               copy_length = length_remaining;
684            }
685            else
686            {
687               copy_length = NC_BLOCK_SIZE;
688            }
689
690            /* copy data to memcard */
691            if (stream_read(sourcef, &nc_card->memcard.memcard_data[block_offset], copy_length)!=copy_length)
692               return IMGTOOLERR_WRITEERROR;
693
694            length_remaining -=copy_length;   
695            file_offset+=copy_length;
696
697            /* mark block as used */
698            memcard_fat_write(&nc_card->memcard,current_block, NC_FAT_END_OF_LIST);
699
700            previous_block = current_block;
701            current_block = memcard_fat_get_free_block(&nc_card->memcard);
702     
703            if (current_block==-1)
704               break;
705         
706            /* link up block chain */
707            memcard_fat_write(&nc_card->memcard,previous_block, current_block|0x02000);
708         }
709     
710         /* end block chain */
711         memcard_fat_write(&nc_card->memcard,current_block, NC_FAT_END_OF_LIST);
712      }
713   }
714
715
716   return 0;
717}
718
719/* directory fills 1 or more blocks.
720current_block holds index of current block we are accessing,
721offset_in_block holds offset within block referenced by current_block.
722eod is 1 if end of directory (no more blocks) or 0 if not end of directory */
723
724struct nc_card_direnum
725{
726   imgtool_directory base;
727   /* card image */
728   struct nc_card_image *img;
729   /* directory block index */
730   int current_block;
731   /* index of entry within block */
732   int offset_in_block;
733   /* true if reached last entry in last directory block */
734   int eod;
735};
736
737
738static int nc_card_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
739{
740   struct nc_card_image *nc_card = (struct nc_card_image *)img;
741   struct nc_card_direnum *card_enum;
742
743   if (memcard_is_executable(&nc_card->memcard))
744   {
745      return IMGTOOLERR_MODULENOTFOUND;
746   }   
747
748   card_enum = (struct nc_card_direnum *) malloc(sizeof(struct nc_card_direnum));
749   if (!card_enum)
750      return IMGTOOLERR_OUTOFMEMORY;
751
752   card_enum->base.module = img->module;
753   card_enum->img = (struct nc_card_image *) img;
754   /* directory always starts on block 2 */
755   card_enum->current_block = 2;
756   card_enum->offset_in_block = 0;
757   card_enum->eod = 0;
758   *outenum = &card_enum->base;
759   return 0;
760}
761
762static int nc_card_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
763{
764   struct nc_card_direnum *card_enum = (struct nc_card_direnum *) enumeration;
765
766   /* got to end of directory? */
767   if (!card_enum->eod)
768   {
769      int quit = 0;
770      /* no */
771
772      /* loop until we get a used directory entry */
773      while (quit==0)
774      {
775         int dir_block_offset;
776         struct nc_card_dir_entry *dir_entry;
777
778         /* gone over end of block? */
779         if (card_enum->offset_in_block==NC_BLOCK_SIZE)
780         {
781            /* yes */
782
783            /* reset offset */
784            card_enum->offset_in_block = 0;
785            /* get next block */
786            card_enum->current_block = memcard_fat_get_next_block(&card_enum->img->memcard,card_enum->current_block);
787
788            /* block index = end of list? */
789            if (card_enum->current_block==NC_FAT_END_OF_LIST)
790            {
791               /* yes */
792
793               /* no more directory blocks, end of directory reached */
794               card_enum->eod = 1;
795     
796               /* no more blocks - so quit */
797               quit = 1;
798            }
799            else
800            {
801               /* strip off upper 4 bits */
802               card_enum->current_block &=0x0fff;
803            }
804         }
805
806         if (quit==0)
807         {
808            dir_block_offset = memcard_block_to_offset(card_enum->current_block);
809
810            dir_entry = (struct nc_card_dir_entry *)&card_enum->img->memcard.memcard_data[dir_block_offset + card_enum->offset_in_block];
811
812            if (dir_entry->filename[0]!=0)
813            {   
814               /* got a used directory entry */
815
816               if (ent->fname_len<13)
817                  return IMGTOOLERR_BUFFERTOOSMALL;
818
819               memcpy(ent->fname, dir_entry->filename,12);
820               dir_entry->filename[12] = '\0';
821
822               /* set file-size -> from directory */
823               ent->filesize = ((dir_entry->size_high_byte & 0x0ff)<<8) | (dir_entry->size_low_byte & 0x0ff);
824
825               /* not last entry */
826               ent->eof = 0;
827               /* not corrupt */
828               ent->corrupt = 0;
829
830               if (ent->attr_len)
831               {   
832                  switch (dir_entry->type)
833                  {
834                     case 0:
835                     {
836                        sprintf(ent->attr,"ASCII FILE");
837                     }
838                     break;
839
840                     case 5:
841                     {
842                        sprintf(ent->attr,"BASIC FILE");
843                     }
844                     break;
845
846                     case 3:
847                     {
848                        sprintf(ent->attr,"DIRECTORY");
849                     }
850                     break;
851                  }
852               }
853
854               quit = 1;
855            }
856         }
857
858         /* update offset for next enum */
859         card_enum->offset_in_block+=32;
860      }
861   }
862
863   /* got to end of directory? */
864   if (card_enum->eod)
865   {
866      /* yes */
867      ent->filesize = 0;
868      ent->corrupt = 0;
869      ent->eof = 1;
870      if (ent->fname_len > 0)
871         ent->fname[0] = '\0';
872   }
873
874   return 0;
875}
876
877static void nc_card_image_closeenum(imgtool_directory *enumeration)
878{
879   free(enumeration);
880}
src/mess/tools/imgtool/ti990hd.c
r1339r1340
1/*
2   Handlers for ti990 disk images
3
4   Disk images are in MESS format.
5
6   Raphael Nabet, 2003
7*/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <limits.h>
13#include <assert.h>
14#include "osdepend.h"
15#include "imgtoolx.h"
16
17/* Max sector lenght is bytes.  Generally 256, except for a few older disk
18units which use 288-byte-long sectors, and SCSI units which generally use
19standard 512-byte-long sectors. */
20/* I chose a limit of 512.  No need to use more until someone creates CD-ROMs
21for TI990. */
22#define MAX_SECTOR_SIZE 512
23#define MIN_SECTOR_SIZE 256
24
25#define MAX_CYLINDERS 2047
26#define MAX_HEADS 31
27#define MAX_SECTORS_PER_TRACK 256   /* 255 for 512-byte-long sector, so that the total number of words that can be recorded on a track may fit in one 16-bit word (store registers command) */
28
29/* Max path len in chars: this value is 48 characters in DX10, but since the
30path includes at least a leading '.', our value is 47. */
31/* Since path generally include a volume name that can be up to 8 character
32long, we should display a warning message when the user wants to create a path
33that is longer than 39 characters. */
34#define MAX_PATH_LEN 47
35#define MAX_SAFE_PATH_LEN 39
36
37#define MAX_DIR_LEVEL 25   /* We need to put a recursion limit to avoid endless recursion hazard */
38 
39
40typedef struct UINT16BE
41{
42   UINT8 bytes[2];
43} UINT16BE;
44
45typedef struct UINT32BE
46{
47   UINT8 bytes[4];
48} UINT32BE;
49
50INLINE UINT16 get_UINT16BE(UINT16BE word)
51{
52   return (word.bytes[0] << 8) | word.bytes[1];
53}
54
55INLINE void set_UINT16BE(UINT16BE *word, UINT16 data)
56{
57   word->bytes[0] = (data >> 8) & 0xff;
58   word->bytes[1] = data & 0xff;
59}
60
61INLINE UINT32 get_UINT32BE(UINT32BE word)
62{
63   return (word.bytes[0] << 24) | (word.bytes[1] << 16) | (word.bytes[2] << 8) | word.bytes[3];
64}
65
66INLINE void set_UINT32BE(UINT32BE *word, UINT32 data)
67{
68   word->bytes[0] = (data >> 24) & 0xff;
69   word->bytes[1] = (data >> 16) & 0xff;
70   word->bytes[2] = (data >> 8) & 0xff;
71   word->bytes[3] = data & 0xff;
72}
73
74/*
75   disk image header
76*/
77typedef struct disk_image_header
78{
79   UINT32BE cylinders;         /* number of cylinders on hard disk (big-endian) */
80   UINT32BE heads;            /* number of heads on hard disk (big-endian) */
81   UINT32BE sectors_per_track;   /* number of sectors per track on hard disk (big-endian) */
82   UINT32BE bytes_per_sector;   /* number of bytes of data per sector on hard disk (big-endian) */
83} disk_image_header;
84
85enum
86{
87   header_len = sizeof(disk_image_header)
88};
89
90/*
91   Disk structure:
92
93   Track 0 Sector 0: see below
94   Track 0 Sector 1: list of bad ADU
95   Track 0 Sector 2 through N: disk allocation bitmap
96   Track 1 Sector 0 through N-2: optional disk program image loader
97   Track 1 Sector N-1: copy of Track 0 Sector 0
98   Track 1 Sector N: copy of Track 0 Sector 1
99   Last cylinder has disagnostic information (reported as .S$DIAG)
100   Remaining sectors are used for fdr and data.
101*/
102
103/*
104   SC0 record (Disk sector 0)
105*/
106typedef struct ti990_sc0
107{
108   char      vnm[8];         /* volume name */
109   UINT16BE   tna;         /* total number of ADUs */
110   UINT8      sbm;         /* starting sector of bit maps */
111   UINT8      tbm;         /* total bit maps */
112   UINT16BE   rl;            /* track 01 record length */
113   UINT16BE   slt;         /* system loader track address */
114   UINT8      fill00[6];      /* * * RESERVED * * */
115   UINT16BE   nba;         /* total number of bad ADUs on disk */
116   UINT16BE   sle;         /* system loader entry point */
117   UINT16BE   sll;         /* system loader length */
118   UINT8      fill01[8];      /* * * RESERVED * * */
119   UINT16BE   lt1;         /* system loader track (copy 2) */
120   UINT8      fill02[8];      /* * * RESERVED * * */
121   char      pi1[8];         /* primary system file name */
122   char      pi2[8];         /* secondary system file name */
123   UINT16BE   pif;         /* system selector */
124   UINT16BE   vda;         /* volume directory ADU */
125   UINT16BE   vpl;         /* vcatalog physical record length */
126   UINT16BE   spa;         /* sectors per ADU */
127   UINT8      dcd[4];         /* disk creation date */
128   char      pf1[8];         /* primary program file */
129   char      pf2[8];         /* secondary program file */
130   UINT16BE   pff;         /* program file switch */
131   char      of1[8];         /* primary overlay file */
132   char      of2[8];         /* secondary overlay file */
133   UINT16BE   off;         /* overlay file switch */
134   char      il1[8];         /* primary intermediate loader */
135   char      il2[8];         /* secondary intermediate loader */
136   UINT16BE   ilf;         /* intermediate loader flag */
137   char      din[8];         /* diagnostic file name */
138   UINT16BE   dif;         /* diagnostic flag */
139   UINT16BE   drs;         /* default physical record size "DBUILD DETERMINES DEFAULT PRS" (whatever it means) */
140   UINT16BE   bal;         /* starting sector of bad ADU list */
141   UINT16BE   spr;         /* track 0 sectors per record */
142   char      wf1[8];         /* WCS primary microcode file */
143   char      wf2[8];         /* WCS secondary microcode file */
144   UINT16BE   wff;         /* WCS flag switch */
145   UINT16BE   vif;         /* track 1 select flag (whatever it means) volume information copied flag */
146   UINT16BE   sta;         /* state of disk: */
147                           /*   1 = disk surface has not been tested for defects */
148                           /*   2 = disk surface has been tested, but no file system has been installed */
149                           /*   3 = a file system has been installed */
150   UINT16BE   dct;         /* disk creation time */
151   UINT16BE   fsf;         /* * * RESERVED * * */
152   /* SCOSIZ = >AA */
153} ti990_sc0;
154
155/*
156   DOR (Directory Overhead Record)
157*/
158typedef struct ti990_dor
159{
160   UINT16BE nrc;            /* # records in directory (minus DOR) nrc = nfl + nar (+ tfc???) */
161   UINT16BE nfl;            /* # files currently in directory */
162   UINT16BE nar;            /* # of available records */
163   UINT16BE tfc;            /* number of temporary files */
164   char dnm[8];            /* directory file name (VCATALOG for root) */
165   UINT16BE lvl;            /* level # of directory (0 for root, 1 for children of root, 2 for grandchildren, etc) */
166   char pnm[8];            /* name of parent directory (VCATALOG for root, even though it makes little sense) */
167   UINT16BE prs;            /* "default physical record length (used for file creation)" */
168   /* DORSIZ = >1C */
169} ti990_dor;
170
171/*
172   file flags found in fdr
173*/
174enum
175{
176   ace_flg_rdf = 0x8000,      /* read access flag */
177   ace_flg_wrf = 0x4000,      /* write access flag */
178   ace_flg_dlf = 0x2000,      /* delete access flag */
179   ace_flg_exf = 0x1000,      /* execute access flag */
180   ace_flg_ctf = 0x0800,      /* control access flag */
181
182   fdr_fl1_sec = 0x8000,      /* file secured flag */
183
184   fdr_flg_fu  = 0xc000,      /* file usage bits */
185   fdr_flg_fu_shift  = 14,
186   fdr_flg_fmt = 0x3000,      /* file format bits */
187   fdr_flg_fmt_shift  = 12,
188   fdr_flg_all = 0x0800,      /* extendable file flag */
189   fdr_flg_ft  = 0x0600,      /* file type bits */
190   fdr_flg_ft_shift  = 9,
191   fdr_flg_wpb = 0x0100,      /* write protect bit */
192   fdr_flg_dpb = 0x0080,      /* delete protect bit */
193   fdr_flg_tmp = 0x0040,      /* temporary file flag */
194   fdr_flg_blb = 0x0020,      /* blocked file flag */
195   fdr_flg_ali = 0x0010,      /* alias flag bit */
196   fdr_flg_fwt = 0x0008,      /* forced write / partial logging */
197   fdr_flg_cdr = 0x0001      /* record is CDR */
198};
199
200/*
201   ACE subrecord found in FDR
202*/
203typedef struct ti990_ace
204{
205   char      agn[8];            /* access group name */
206   UINT16BE   flg;            /* flags */
207} ti990_ace;
208
209/*
210   FDR record
211*/
212typedef struct ti990_fdr
213{
214   UINT16BE   hkc;         /* hask key count: the number of file descriptor records that are present in the directory that hashed to this record number */
215   UINT16BE   hkv;         /* hask key value: the result of the hash algorithm for the file name actually covered in this record */
216   char      fnm[8];         /* file name */
217   UINT8      rsv[2];         /* reserved */
218   UINT16BE   fl1;         /* flags word 1 */
219   UINT16BE   flg;         /* flags word 2 */
220   UINT16BE   prs;         /* physical record size */
221   UINT16BE   lrs;         /* logical record size */
222   UINT16BE   pas;         /* primary allocation size: # of ADUs allocated in primary allocation block? */
223   UINT16BE   paa;         /* primary allocation address: first ADU of primary allocation block? */
224   UINT16BE   sas;         /* secondary allocation size: used to determinate the # of blocks allocated per secondary allocation */
225   UINT16BE   saa;         /* offset of secondary table: ???? "offset into this FDR of the secondary allocation table, if any.  No secondary allocation table is denoted by 0.  Secondary allocations are present only for unbounded files." */
226   UINT16BE   rfa;         /* record number of first alias */
227   UINT32BE   eom;         /* end of medium record number */
228   UINT32BE   bkm;         /* end of medium block number */
229   UINT16BE   ofm;         /* end of medium offset / */
230                           /* prelog number for KIF */
231   UINT32BE   fbq;         /* free block queue head */
232   UINT16BE   btr;         /* B-tree roots block # */
233   UINT32BE   ebq;         /* empty block queue head */
234   UINT16BE   kdr;         /* key descriptions record # */
235   UINT8      ud[6];         /* last update date */
236   UINT8      cd[6];         /* creation date */
237   UINT8      apb;         /* ADU's per block */
238   UINT8      bpa;         /* blocks per ADU */
239   UINT16BE   mrs;         /* minimumu KIF record size */
240   UINT8      sat[64];      /* secondary allocation table: 16 2-word entries.  The first word of an entry contains the size, in ADUs, of the secondary allocation.  The second word contains the starting ADU of the allocation. */
241
242/* bytes >86 to >100 are optional */
243   UINT8      res[10];      /* reserved: seem to be actually meaningful (at least under DX10 3.6.x) */
244   char      uid[8];         /* user id of file creator */
245   UINT16BE   psa;         /* public security attribute */
246   ti990_ace   ace[9];         /* 9 access control entries */
247   UINT8      fil[2];         /* not used */
248} ti990_fdr;
249
250/*
251   ADR record: variant of FDR for Aliases
252
253   The fields marked here with *** are in the ADR template to maintain
254   compatability with the FDR template.
255*/
256typedef struct ti990_adr
257{
258   UINT16BE   hkc;         /* hask key count */
259   UINT16BE   hkv;         /* hask key value */
260   char      fnm[8];         /* file name */
261   char      psw[4];         /* "password" (whatever it means) */
262   UINT16BE   flg;         /* flags (same as fdr.flg) */
263   UINT16BE   fill00;         /* *** physical record size */
264   UINT16BE   fill01;         /* *** logical record size */
265   UINT16BE   fill02;         /* *** primary allocation size */
266   UINT16BE   fill03;         /* *** primary allocation address */
267   UINT16BE   fill04;         /* *** secondary allocation size */
268   UINT16BE   fill05;         /* *** secondary allocation address */
269   UINT16BE   rna;         /* record number of next ADR */
270   UINT16BE   raf;         /* record # of actual FDR (from 1 through dor.nrc) */
271} ti990_adr;
272
273/*
274   CDR record: variant of FDR for Channel
275
276   The CDR is the permanent record of a channel.  It is carried as an alias
277   of the program file in which the channel owner task resides.
278*/
279typedef struct ti990_cdr
280{
281   UINT16BE   hkc;         /* hask key count */
282   UINT16BE   hkv;         /* hask key value */
283   char      fnm[8];         /* file name */
284   UINT16BE   fill00;         /* reserved */
285   UINT16BE   fill01;         /* reserved */
286   UINT16BE   fdf;         /* flags (same as fdr.flg) */
287   UINT8      flg;         /* channel flzgs */
288   UINT8      iid;         /* owner task installed ID */
289   UINT8      typ;         /* default resource type */
290   UINT8      tf;            /* resource type flags */
291   UINT16BE   mxl;         /* maximum message length */
292   UINT8      fill04[6];      /* reserved (and, no, I don't know where fill02 and fill03 have gone) */
293   UINT16BE   rna;         /* record number of next CDR or ADR */
294   UINT16BE   raf;         /* record # of actual FDR */
295   UINT8      fill05[110];   /* reserved */
296   char      uid[8];         /* user ID of channel creator */
297   UINT16BE   psa;         /* public security attribute */
298   UINT8      scg[94];      /* "SDT with 9 control groups" (whatever it means - and, no, 94 is not dividable by 9) */
299   UINT8      fill06[8];      /* reserved */
300} ti990_cdr;
301
302/*
303   Based on contents of the flags field, catalog entries may be either an FDR,
304   an ADR or a CDR.
305
306   They may be a KDR, too, but confusion is impossible because the KDR FILL00
307   field starts at offset 4, and therefore if we try to interpret a KDR as an
308   FDR (or ADR, CDR), we will find fnm[0] and assume the FDR is empty.
309*/
310typedef union directory_entry
311{
312   ti990_fdr fdr;
313   ti990_adr adr;
314   ti990_cdr cdr;
315} directory_entry;
316
317#if 0
318
319/*
320   tifile header: stand-alone file
321*/
322typedef struct tifile_header
323{
324   char tifiles[8];      /* always '\7TIFILES' */
325   UINT8 secsused_MSB;      /* file length in sectors (big-endian) */
326   UINT8 secsused_LSB;
327   UINT8 flags;         /* see enum above */
328   UINT8 recspersec;      /* records per sector */
329   UINT8 eof;            /* current position of eof in last sector (0->255)*/
330   UINT8 reclen;         /* bytes per record ([1,255] 0->256) */
331   UINT8 fixrecs_MSB;      /* file length in records (big-endian) */
332   UINT8 fixrecs_LSB;
333   UINT8 res[128-16];      /* reserved */
334} tifile_header;
335
336
337/*
338   catalog entry (used for in-memory catalog)
339*/
340typedef struct catalog_entry
341{
342   UINT16 fdr_secnum;
343   char filename[10];
344} catalog_entry;
345
346#endif
347
348/*
349   Disk geometry
350*/
351typedef struct ti990_geometry
352{
353   unsigned int cylinders, heads, sectors_per_track, bytes_per_sector;
354} ti990_geometry;
355
356/*
357   Physical sector address
358*/
359typedef struct ti990_phys_sec_address
360{
361   int cylinder;
362   int head;
363   int sector;
364} ti990_phys_sec_address;
365
366/*
367   ti99 disk image descriptor
368*/
369typedef struct ti990_image
370{
371   imgtool_stream *file_handle;      /* imgtool file handle */
372   ti990_geometry geometry;   /* geometry */
373   ti990_sc0 sec0;            /* cached copy of sector 0 */
374} ti990_image;
375
376/*
377   ti990 catalog iterator, used when imgtool reads the catalog
378*/
379typedef struct ti990_iterator
380{
381   ti990_image *image;
382   int level;                     /* current recursion level */
383   int nrc[MAX_DIR_LEVEL];            /* length of disk catalogs in records */
384   int index[MAX_DIR_LEVEL];         /* current index in the disk catalog */
385   directory_entry xdr[MAX_DIR_LEVEL];   /* fdr records */
386} ti990_iterator;
387
388
389static imgtoolerr_t ti990_image_init(imgtool_image *img, imgtool_stream *f);
390static void ti990_image_exit(imgtool_image *img);
391static void ti990_image_info(imgtool_image *img, char *string, size_t len);
392static imgtoolerr_t ti990_image_beginenum(imgtool_directory *enumeration, const char *path);
393static imgtoolerr_t ti990_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
394static void ti990_image_closeenum(imgtool_directory *enumeration);
395static imgtoolerr_t ti990_image_freespace(imgtool_partition *partition, UINT64 *size);
396#ifdef UNUSED_FUNCTION
397static imgtoolerr_t ti990_image_readfile(imgtool_partition *partition, const char *fpath, imgtool_stream *destf);
398static imgtoolerr_t ti990_image_writefile(imgtool_partition *partition, const char *fpath, imgtool_stream *sourcef, option_resolution *writeoptions);
399static imgtoolerr_t ti990_image_deletefile(imgtool_partition *partition, const char *fpath);
400#endif
401static imgtoolerr_t ti990_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions);
402
403enum
404{
405   /*ti990_createopts_volname = 'A',*/
406   ti990_createopts_cylinders = 'B',
407   ti990_createopts_heads = 'C',
408   ti990_createopts_sectors = 'D',
409   ti990_createopts_sectorsize = 'E'
410};
411
412OPTION_GUIDE_START( ti990_create_optionguide )
413   /*OPTION_STRING(ti990_createopts_volname, "label",   "Volume name" )*/
414   OPTION_INT(ti990_createopts_cylinders, "cylinders", "Cylinders" )
415   OPTION_INT(ti990_createopts_heads, "heads", "Heads" )
416   OPTION_INT(ti990_createopts_sectors, "sectors", "Sectors" )
417   OPTION_INT(ti990_createopts_sectorsize, "bytes per sector (typically 256)", "Bytes Per Sector" )
418OPTION_GUIDE_END
419
420#define symb2str2(a) #a
421#define symb2str(a) symb2str2(a)
422#define ti990_create_optionspecs "B1-[145]-"symb2str(MAX_CYLINDERS)";C1-[4]-"symb2str(MAX_HEADS)";D1-[32]-"symb2str(MAX_SECTORS_PER_TRACK)";E"symb2str(MIN_SECTOR_SIZE)"-[256]-"symb2str(MAX_SECTOR_SIZE)";"
423
424void ti990_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
425{
426   switch(state)
427   {
428      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "ti990hd"); break;
429      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "TI990 Hard Disk"); break;
430      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "hd"); break;
431      case IMGTOOLINFO_STR_EOLN:                     /* strcpy(info->s = imgtool_temp_str(), "\r"); */ break;
432
433      case IMGTOOLINFO_PTR_OPEN:                     info->open = ti990_image_init; break;
434      case IMGTOOLINFO_PTR_CLOSE:                     info->close = ti990_image_exit; break;
435      case IMGTOOLINFO_PTR_INFO:                     info->info = ti990_image_info; break;
436      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = ti990_image_beginenum; break;
437      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = ti990_image_nextenum; break;
438      case IMGTOOLINFO_PTR_CLOSE_ENUM:               info->close_enum = ti990_image_closeenum; break;
439      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = ti990_image_freespace; break;
440      case IMGTOOLINFO_PTR_READ_FILE:                  /* info->read_file = ti990_image_readfile; */ break;
441      case IMGTOOLINFO_PTR_WRITE_FILE:               /* info->write_file = ti990_image_writefile; */ break;
442      case IMGTOOLINFO_PTR_DELETE_FILE:               /* info->delete_file = ti990_image_deletefile; */ break;
443      case IMGTOOLINFO_PTR_CREATE:                  info->create = ti990_image_create; break;
444
445      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:         info->createimage_optguide = ti990_create_optionguide; break;
446      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:         strcpy(info->s = imgtool_temp_str(), ti990_create_optionspecs); break;
447   }
448}
449
450#ifdef UNUSED_FUNCTION
451/*
452   Convert a C string to a 8-character file name (padded with spaces if necessary)
453*/
454static void str_to_fname(char dst[8], const char *src)
455{
456   int i;
457
458
459   i = 0;
460
461   /* copy 8 characters at most */
462   if (src)
463      while ((i<8) && (src[i]!='\0'))
464      {
465         dst[i] = src[i];
466         i++;
467      }
468
469   /* pad with spaces */
470   while (i<8)
471   {
472      dst[i] = ' ';
473      i++;
474   }
475}
476#endif
477
478/*
479   Convert a 8-character file name to a C string (removing trailing spaces if necessary)
480*/
481static void fname_to_str(char *dst, const char src[8], int n)
482{
483   int i;
484   int last_nonspace;
485
486
487   /* copy 8 characters at most */
488   if (--n > 8)
489      n = 8;
490
491   /* copy filename */
492   i = 0;
493   last_nonspace = -1;
494
495   while (i<n)
496   {
497      dst[i] = src[i];
498      if (src[i] != ' ')
499         last_nonspace = i;
500      i++;
501   }
502
503   /* terminate with '\0' */
504   dst[last_nonspace+1] = '\0';
505}
506
507#if 0
508#pragma mark -
509#pragma mark DISK ROUTINES
510#endif
511
512/*
513   Convert physical sector address to offset
514*/
515static unsigned phys_address_to_offset(const ti990_phys_sec_address *address, const ti990_geometry *geometry)
516{
517   unsigned offset;
518
519   /* current MESS format */
520   offset = (((address->cylinder*geometry->heads) + address->head)*geometry->sectors_per_track + address->sector)*geometry->bytes_per_sector + header_len;
521
522   return offset;
523}
524
525/*
526   Read one sector from a disk image
527
528   file_handle: imgtool file handle
529   address: physical sector address
530   geometry: disk geometry (sectors per track, tracks per side, sides)
531   dest: pointer to destination buffer
532   len: lenght of data to read
533*/
534static int read_sector_physical_len(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, void *dest, int len)
535{
536   int reply;
537
538   if (len > geometry->bytes_per_sector)
539      return 1;
540
541   /* seek to sector */
542   reply = stream_seek(file_handle, phys_address_to_offset(address, geometry), SEEK_SET);
543   if (reply)
544      return 1;
545   /* read it */
546   reply = stream_read(file_handle, dest, len);
547   if (reply != len)
548      return 1;
549
550   return 0;
551}
552
553#ifdef UNUSED_FUNCTION
554/*
555   Read one sector from a disk image
556
557   file_handle: imgtool file handle
558   address: physical sector address
559   geometry: disk geometry (sectors per track, tracks per side, sides)
560   dest: pointer to a destination buffer of geometry->bytes_per_sector bytes
561*/
562static int read_sector_physical(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, void *dest)
563{
564   return read_sector_physical_len(file_handle, address, geometry, dest, geometry->bytes_per_sector);
565}
566#endif
567
568/*
569   Write one sector to a disk image
570
571   file_handle: imgtool file handle
572   address: physical sector address
573   geometry: disk geometry (sectors per track, tracks per side, sides)
574   src: pointer to source buffer
575   len: lenght of source buffer
576*/
577static int write_sector_physical_len(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, const void *src, int len)
578{
579   int reply;
580
581   if (len > geometry->bytes_per_sector)
582      return 1;
583
584   /* seek to sector */
585   reply = stream_seek(file_handle, phys_address_to_offset(address, geometry), SEEK_SET);
586   if (reply)
587      return 1;
588   /* write it */
589   reply = stream_write(file_handle, src, len);
590   if (reply != len)
591      return 1;
592   /* pad with 0s if needed */
593   if (len < geometry->bytes_per_sector)
594   {
595      reply = stream_fill(file_handle, 0, geometry->bytes_per_sector - len);
596
597      if (reply != geometry->bytes_per_sector - len)
598         return 1;
599   }
600
601   return 0;
602}
603
604#ifdef UNUSED_FUNCTION
605/*
606   Write one sector to a disk image
607
608   file_handle: imgtool file handle
609   address: physical sector address
610   geometry: disk geometry (sectors per track, tracks per side, sides)
611   dest: pointer to a source buffer of geometry->bytes_per_sector bytes
612*/
613static int write_sector_physical(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, const void *src)
614{
615   return write_sector_physical_len(file_handle, address, geometry, src, geometry->bytes_per_sector);
616}
617#endif
618
619/*
620   Convert logical sector address to physical sector address
621*/
622static void log_address_to_phys_address(int secnum, const ti990_geometry *geometry, ti990_phys_sec_address *address)
623{
624   address->sector = secnum % geometry->sectors_per_track;
625   secnum /= geometry->sectors_per_track;
626   address->head = secnum % geometry->heads;
627   address->cylinder = secnum / geometry->heads;
628}
629
630/*
631   Read one sector from a disk image
632
633   file_handle: imgtool file handle
634   secnum: logical sector address
635   geometry: disk geometry (sectors per track, tracks per side, sides)
636   dest: pointer to destination buffer
637   len: lenght of data to read
638*/
639static int read_sector_logical_len(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, void *dest, int len)
640{
641   ti990_phys_sec_address address;
642
643
644   log_address_to_phys_address(secnum, geometry, &address);
645
646   return read_sector_physical_len(file_handle, &address, geometry, dest, len);
647}
648
649#ifdef UNUSED_FUNCTION
650/*
651   Read one sector from a disk image
652
653   file_handle: imgtool file handle
654   secnum: logical sector address
655   geometry: disk geometry (sectors per track, tracks per side, sides)
656   dest: pointer to a destination buffer of geometry->bytes_per_sector bytes
657*/
658static int read_sector_logical(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, void *dest)
659{
660   return read_sector_logical_len(file_handle, secnum, geometry, dest, geometry->bytes_per_sector);
661}
662#endif
663
664/*
665   Write one sector to a disk image
666
667   file_handle: imgtool file handle
668   secnum: logical sector address
669   geometry: disk geometry (sectors per track, tracks per side, sides)
670   src: pointer to source buffer
671   len: lenght of source buffer
672*/
673static int write_sector_logical_len(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, const void *src, int len)
674{
675   ti990_phys_sec_address address;
676
677
678   log_address_to_phys_address(secnum, geometry, &address);
679
680   return write_sector_physical_len(file_handle, &address, geometry, src, len);
681}
682
683/*
684   Write one sector to a disk image
685
686   file_handle: imgtool file handle
687   secnum: logical sector address
688   geometry: disk geometry (sectors per track, tracks per side, sides)
689   dest: pointer to a source buffer of geometry->bytes_per_sector bytes
690*/
691static int write_sector_logical(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, const void *src)
692{
693   return write_sector_logical_len(file_handle, secnum, geometry, src, geometry->bytes_per_sector);
694}
695
696#if 0
697#pragma mark -
698#pragma mark CATALOG FILE ROUTINES
699#endif
700
701#ifdef UNUSED_FUNCTION
702/*
703   Find the catalog entry and fdr record associated with a file name
704
705   image: ti990_image image record
706   fpath: path of the file to search
707   fdr: pointer to buffer where the fdr record should be stored (may be NULL)
708   catalog_index: on output, index of file catalog entry (may be NULL)
709   out_fdr_secnum: on output, sector address of the fdr (may be NULL)
710   out_parent_fdr_secnum: on output, sector offset of the fdr for the parent
711      directory fdr (-1 if root) (may be NULL)
712*/
713static int find_fdr(ti990_image *image, const char fpath[MAX_PATH_LEN+1], int *catalog_index, int *out_fdr_secnum, int *out_parent_fdr_secnum)
714{
715   int fdr_secnum = -1, parent_fdr_secnum;
716   int i;
717   const char *element_start, *element_end;
718   int element_len;
719   char element[8];
720   ti990_dor dor;
721   directory_entry xdr;
722   int hash_key;
723   int nrc;
724   unsigned base;
725   int reply;
726   int flag;
727
728
729   base = (unsigned) get_UINT16BE(image->sec0.vda) * get_UINT16BE(image->sec0.spa);
730
731   element_start = fpath;
732   do
733   {
734      /* read directory header */
735      reply = read_sector_logical_len(image->file_handle, base, & image->geometry, &dor, sizeof(dor));
736      if (reply)
737         return IMGTOOLERR_READERROR;
738
739      nrc = get_UINT16BE(dor.nrc);
740
741      /* find next path element */
742      element_end = strchr(element_start, '.');
743      element_len = element_end ? (element_end - element_start) : strlen(element_start);
744      if ((element_len > 8) || (element_len == 0))
745         return IMGTOOLERR_BADFILENAME;
746      /* generate file name and hash key */
747      hash_key = 1;
748      for (i=0; i<element_len; i++)
749      {
750         element[i] = element_start[i];
751         hash_key = ((hash_key * (unsigned char) element_start[i]) % nrc) + 1;
752      }
753      while (i<8)
754      {
755         element[i] = ' ';
756         i++;
757      }
758
759      /* search entry in directory */
760      i = hash_key;
761      while (1)
762      {
763         reply = read_sector_logical_len(image->file_handle, base + i, & image->geometry,
764                                    & xdr, 0x86);
765         if (reply)
766            return IMGTOOLERR_READERROR;
767         if (!memcmp(element, xdr.fdr.fnm, 8))
768         {   /* found match !!! */
769            parent_fdr_secnum = fdr_secnum;
770            fdr_secnum = base + i;
771            break;
772         }
773
774         /* next record */
775         if (i != nrc)
776            i++;
777         else
778            i = 1;
779
780         /* exit if we have tested every record */
781         if (i == hash_key)
782            return IMGTOOLERR_FILENOTFOUND;
783      }
784
785      /* iterate */
786      if (element_end)
787      {
788         element_start = element_end+1;
789         /* we need to check that this is a directory */
790         /* if it is an alias to a directory, we need to follow it, too. */
791
792         /* parse flags */
793         flag = get_UINT16BE(xdr.fdr.flg);
794
795         if (flag & fdr_flg_ali)
796         {
797            /* read original fdr */
798            reply = read_sector_logical_len(image->file_handle, base + get_UINT16BE(xdr.adr.raf),
799                                       & image->geometry, & xdr, 0x86);
800
801            flag = get_UINT16BE(xdr.fdr.flg);
802         }
803
804         if (flag & fdr_flg_cdr)
805            /* This is a channel, not a file */
806            return IMGTOOLERR_BADFILENAME;
807         else if (flag & fdr_flg_ali)
808            /* WTH??? */
809            return IMGTOOLERR_CORRUPTIMAGE;
810         else if (((flag >> fdr_flg_fu_shift) & 3) != 1)
811         {
812            /* This file is not a directory */
813            return IMGTOOLERR_BADFILENAME;
814         }
815
816         /* initialize base */
817         base = (unsigned) get_UINT16BE(xdr.fdr.paa) * get_UINT16BE(image->sec0.spa);
818      }
819      else
820         element_start = NULL;
821   }
822   while (element_start);
823
824   if (catalog_index)
825      *catalog_index = i;
826
827   if (out_fdr_secnum)
828      *out_fdr_secnum = fdr_secnum;
829
830   if (out_parent_fdr_secnum)
831      *out_parent_fdr_secnum = parent_fdr_secnum;
832
833   return 0;
834}
835#endif
836
837#if 0
838/*
839   Allocate one sector on disk, for use as a fdr record
840
841   image: ti99_image image record
842   fdr_secnum: on output, logical address of a free sector
843*/
844static int alloc_fdr_sector(ti99_image *image, int *fdr_secnum)
845{
846   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
847   int i;
848
849
850   for (i=0; i<totsecs; i++)
851   {
852      if (! (image->sec0.abm[i >> 3] & (1 << (i & 7))))
853      {
854         *fdr_secnum = i;
855         image->sec0.abm[i >> 3] |= 1 << (i & 7);
856
857         return 0;
858      }
859   }
860
861   return IMGTOOLERR_NOSPACE;
862}
863
864/*
865   Extend a file with nb_alloc_sectors extra sectors
866
867   image: ti99_image image record
868   fdr: file fdr record
869   nb_alloc_sectors: number of sectors to allocate
870*/
871static int alloc_file_sectors(ti99_image *image, ti99_fdr *fdr, int nb_alloc_sectors)
872{
873   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
874   int free_sectors;
875   int secsused;
876   int i;
877   int lnks_index;
878   int cur_sec, last_sec, p_last_sec;
879   int cur_block_len, cur_block_start;
880   int first_best_block_len, first_best_block_start = 0;
881   int second_best_block_len, second_best_block_start = 0;
882   int search_start;
883
884   /* compute free space */
885   free_sectors = 0;
886   for (i=0; i<totsecs; i++)
887   {
888      if (! (image->sec0.abm[i >> 3] & (1 << (i & 7))))
889         free_sectors++;
890   }
891
892   /* check we have enough free space */
893   if (free_sectors < nb_alloc_sectors)
894      return IMGTOOLERR_NOSPACE;
895
896   /* current number of data sectors in file */
897   secsused = get_fdr_secsused(fdr);
898
899   if (secsused == 0)
900   {   /* links array must be empty */
901      lnks_index = 0;
902   }
903   else
904   {   /* try to extend last block */
905      last_sec = -1;
906      for (lnks_index=0; lnks_index<76; lnks_index++)
907      {
908         p_last_sec = last_sec;
909         last_sec = (fdr->lnks[lnks_index][2] << 4) | (fdr->lnks[lnks_index][1] >> 4);
910         if (last_sec >= (secsused-1))
911            break;
912      }
913      if (lnks_index == 76)
914         /* that sucks */
915         return IMGTOOLERR_CORRUPTIMAGE;
916
917      if (last_sec > (secsused-1))
918      {   /* some extra space has already been allocated */
919         cur_block_len = last_sec - (secsused-1);
920         if (cur_block_len > nb_alloc_sectors)
921            cur_block_len = nb_alloc_sectors;
922
923         secsused += cur_block_len;
924         set_fdr_secsused(fdr, secsused);
925         nb_alloc_sectors -= cur_block_len;
926         if (! nb_alloc_sectors)
927            return 0;   /* done */
928      }
929
930      /* block base */
931      cur_sec = ((fdr->lnks[lnks_index][1] & 0xf) << 8) | fdr->lnks[lnks_index][0];
932      /* point past block end */
933      cur_sec += last_sec-p_last_sec;
934      /* count free sectors after last block */
935      cur_block_len = 0;
936      for (i=cur_sec; (! (image->sec0.abm[i >> 3] & (1 << (i & 7)))) && (cur_block_len < nb_alloc_sectors) && (i < totsecs); i++)
937         cur_block_len++;
938      if (cur_block_len)
939      {   /* extend last block */
940         secsused += cur_block_len;
941         set_fdr_secsused(fdr, secsused);
942         last_sec += cur_block_len;
943         nb_alloc_sectors -= cur_block_len;
944         fdr->lnks[lnks_index][1] = (fdr->lnks[lnks_index][1] & 0x0f) | (last_sec << 4);
945         fdr->lnks[lnks_index][2] = last_sec >> 4;
946         for (i=0; i<cur_block_len; i++)
947            image->sec0.abm[(i+cur_sec) >> 3] |= 1 << ((i+cur_sec) & 7);
948         if (! nb_alloc_sectors)
949            return 0;   /* done */
950      }
951      lnks_index++;
952      if (lnks_index == 76)
953         /* that sucks */
954         return IMGTOOLERR_NOSPACE;
955   }
956
957   search_start = image->data_offset;   /* initially, search for free space only in data space */
958   while (nb_alloc_sectors)
959   {
960      /* find smallest data block at least nb_alloc_sectors in lenght, and largest data block less than nb_alloc_sectors in lenght */
961      first_best_block_len = INT_MAX;
962      second_best_block_len = 0;
963      for (i=search_start; i<totsecs; i++)
964      {
965         if (! (image->sec0.abm[i >> 3] & (1 << (i & 7))))
966         {   /* found one free block */
967            /* compute its lenght */
968            cur_block_start = i;
969            cur_block_len = 0;
970            while ((i<totsecs) && (! (image->sec0.abm[i >> 3] & (1 << (i & 7)))))
971            {
972               cur_block_len++;
973               i++;
974            }
975            /* compare to previous best and second-best blocks */
976            if ((cur_block_len < first_best_block_len) && (cur_block_len >= nb_alloc_sectors))
977            {
978               first_best_block_start = cur_block_start;
979               first_best_block_len = cur_block_len;
980               if (cur_block_len == nb_alloc_sectors)
981                  /* no need to search further */
982                  break;
983            }
984            else if ((cur_block_len > second_best_block_len) && (cur_block_len < nb_alloc_sectors))
985            {
986               second_best_block_start = cur_block_start;
987               second_best_block_len = cur_block_len;
988            }
989         }
990      }
991
992      if (first_best_block_len != INT_MAX)
993      {   /* found one contiguous block which can hold it all */
994         secsused += nb_alloc_sectors;
995         set_fdr_secsused(fdr, secsused);
996
997         fdr->lnks[lnks_index][0] = first_best_block_start;
998         fdr->lnks[lnks_index][1] = ((first_best_block_start >> 8) & 0x0f) | ((secsused-1) << 4);
999         fdr->lnks[lnks_index][2] = (secsused-1) >> 4;
1000         for (i=0; i<nb_alloc_sectors; i++)
1001            image->sec0.abm[(i+first_best_block_start) >> 3] |= 1 << ((i+first_best_block_start) & 7);
1002
1003         nb_alloc_sectors = 0;
1004      }
1005      else if (second_best_block_len != 0)
1006      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
1007         secsused += second_best_block_len;
1008         set_fdr_secsused(fdr, secsused);
1009
1010         fdr->lnks[lnks_index][0] = second_best_block_start;
1011         fdr->lnks[lnks_index][1] = ((second_best_block_start >> 8) & 0x0f) | ((secsused-1) << 4);
1012         fdr->lnks[lnks_index][2] = (secsused-1) >> 4;
1013         for (i=0; i<second_best_block_len; i++)
1014            image->sec0.abm[(i+second_best_block_start) >> 3] |= 1 << ((i+second_best_block_start) & 7);
1015
1016         nb_alloc_sectors -= second_best_block_len;
1017
1018         lnks_index++;
1019         if (lnks_index == 76)
1020            /* that sucks */
1021            return IMGTOOLERR_NOSPACE;
1022      }
1023      else if (search_start != 0)
1024      {   /* we did not find any free sector in the data section of the disk */
1025         search_start = 0;   /* time to fall back to fdr space */
1026      }
1027      else
1028         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
1029   }
1030
1031   return 0;
1032}
1033
1034/*
1035   Allocate a new (empty) file
1036*/
1037static int new_file(ti99_image *image, char filename[10], int *out_fdr_secnum/*, ti99_fdr *fdr,*/)
1038{
1039   int fdr_secnum;
1040   int catalog_index, i;
1041   int reply = 0;
1042
1043
1044   /* find insertion point in catalog */
1045   i = 0;
1046   if ((image->catalog[0].fdr_secnum == 0) && (image->catalog[1].fdr_secnum != 0))
1047      i = 1;   /* skip empty entry 0 (it must be a non-listable catalog) */
1048
1049   for (; (i<128) && ((fdr_secnum = image->catalog[i].fdr_secnum) != 0) && ((reply = memcmp(image->catalog[i].filename, filename, 10)) < 0); i++)
1050      ;
1051
1052   if (i == 128)
1053      /* catalog is full */
1054      return IMGTOOLERR_NOSPACE;
1055   else if (fdr_secnum && (reply == 0))
1056      /* file already exists */
1057      return IMGTOOLERR_BADFILENAME;
1058   else
1059   {
1060      catalog_index = i;
1061      reply = alloc_fdr_sector(image, &fdr_secnum);
1062      if (reply)
1063         return reply;
1064
1065      /* look for first free entry in catalog */
1066      for (i=catalog_index; image->catalog[i].fdr_secnum != 0; i++)
1067         ;
1068
1069      if (i == 128)
1070         /* catalog is full */
1071            return IMGTOOLERR_NOSPACE;
1072
1073      /* shift catalog entries until the insertion point */
1074      for (/*i=127*/; i>catalog_index; i--)
1075         image->catalog[i] = image->catalog[i-1];
1076
1077      /* write new catalog entry */
1078      image->catalog[catalog_index].fdr_secnum = fdr_secnum;
1079      memcpy(image->catalog[catalog_index].filename, filename, 10);
1080      if (out_fdr_secnum)
1081         *out_fdr_secnum = fdr_secnum;
1082   }
1083
1084   return 0;
1085}
1086
1087/*
1088   Compare two (possibly empty) catalog entry for qsort
1089*/
1090static int qsort_catalog_compare(const void *p1, const void *p2)
1091{
1092   const catalog_entry *entry1 = p1;
1093   const catalog_entry *entry2 = p2;
1094
1095   if ((entry1->fdr_secnum == 0) && (entry2->fdr_secnum == 0))
1096      return 0;
1097   else if (entry1->fdr_secnum == 0)
1098      return +1;
1099   else if (entry2->fdr_secnum == 0)
1100      return -1;
1101   else
1102      return memcmp(entry1->filename, entry2->filename, 10);
1103}
1104#endif
1105
1106/*
1107   Open a file as a ti990_image.
1108*/
1109static imgtoolerr_t ti990_image_init(imgtool_image *img, imgtool_stream *f)
1110{
1111   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1112   disk_image_header header;
1113   int reply;
1114   unsigned totsecs;
1115
1116   image->file_handle = f;
1117   reply = stream_read(f, &header, sizeof(header));
1118   if (reply != sizeof(header))
1119      return IMGTOOLERR_READERROR;
1120
1121   image->geometry.cylinders = get_UINT32BE(header.cylinders);
1122   image->geometry.heads = get_UINT32BE(header.heads);
1123   image->geometry.sectors_per_track = get_UINT32BE(header.sectors_per_track);
1124   image->geometry.bytes_per_sector = get_UINT32BE(header.bytes_per_sector);
1125
1126   totsecs = image->geometry.cylinders*image->geometry.heads*image->geometry.sectors_per_track;
1127
1128   if ((image->geometry.bytes_per_sector < MIN_SECTOR_SIZE)
1129      || (image->geometry.bytes_per_sector > MAX_SECTOR_SIZE)
1130      || (image->geometry.sectors_per_track > MAX_SECTORS_PER_TRACK)
1131      || (image->geometry.heads > MAX_HEADS)
1132      || (image->geometry.cylinders > MAX_CYLINDERS)
1133      || (totsecs < 1)
1134      || (stream_size(f) != header_len + totsecs*image->geometry.bytes_per_sector))
1135   {
1136      return IMGTOOLERR_CORRUPTIMAGE;
1137   }
1138
1139   {
1140      ti990_phys_sec_address address = { 0, 0, 0 };
1141      reply = read_sector_physical_len(f, &address, &image->geometry, & image->sec0, sizeof(image->sec0));
1142   }
1143   if (reply)
1144   {
1145      return IMGTOOLERR_READERROR;
1146   }
1147
1148   if ((get_UINT16BE(image->sec0.tna)*get_UINT16BE(image->sec0.spa) > totsecs)
1149      || ((get_UINT16BE(image->sec0.spa) != 1) && (get_UINT16BE(image->sec0.spa) % 3)))
1150   {
1151      return IMGTOOLERR_CORRUPTIMAGE;
1152   }
1153
1154   if ((get_UINT16BE(image->sec0.vpl) != 0x86) && (get_UINT16BE(image->sec0.vpl) != 0x100))
1155   {
1156      return IMGTOOLERR_CORRUPTIMAGE;
1157   }
1158
1159   return IMGTOOLERR_SUCCESS;
1160}
1161
1162/*
1163   close a ti990_image
1164*/
1165static void ti990_image_exit(imgtool_image *img)
1166{
1167   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1168   stream_close(image->file_handle);
1169}
1170
1171/*
1172   get basic information on a ti990_image
1173
1174   Currently returns the volume name
1175*/
1176static void ti990_image_info(imgtool_image *img, char *string, size_t len)
1177{
1178   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1179   char vol_name[9];
1180
1181   fname_to_str(vol_name, image->sec0.vnm, 9);
1182
1183   snprintf(string, len, "%s", vol_name);
1184}
1185
1186/*
1187   Open the disk catalog for enumeration
1188*/
1189static imgtoolerr_t ti990_image_beginenum(imgtool_directory *enumeration, const char *path)
1190{
1191   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
1192   ti990_iterator *iter = (ti990_iterator *) imgtool_directory_extrabytes(enumeration);
1193   ti990_dor dor;
1194   int reply;
1195
1196   iter->image = image;
1197
1198   reply = read_sector_logical_len(iter->image->file_handle,
1199                           (unsigned) get_UINT16BE(iter->image->sec0.vda) * get_UINT16BE(iter->image->sec0.spa),
1200                           & iter->image->geometry, &dor, sizeof(dor));
1201
1202   if (reply)
1203      return IMGTOOLERR_READERROR;
1204
1205   iter->level = 0;
1206   iter->nrc[0] = get_UINT16BE(dor.nrc);
1207   iter->index[0] = 0;
1208
1209   return IMGTOOLERR_SUCCESS;
1210}
1211
1212/*
1213   Enumerate disk catalog next entry
1214*/
1215static imgtoolerr_t ti990_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
1216{
1217   ti990_iterator *iter = (ti990_iterator *) imgtool_directory_extrabytes(enumeration);
1218   int flag;
1219   int reply = 0;
1220
1221
1222   ent->corrupt = 0;
1223   ent->eof = 0;
1224
1225   while ((iter->level >= 0)
1226         && (! (reply = read_sector_logical_len(iter->image->file_handle,
1227                                       iter->level ? (unsigned) get_UINT16BE(iter->xdr[iter->level-1].fdr.paa) * get_UINT16BE(iter->image->sec0.spa) + (iter->index[iter->level]+1)
1228                                                : (unsigned) get_UINT16BE(iter->image->sec0.vda) * get_UINT16BE(iter->image->sec0.spa) + (iter->index[iter->level]+1),
1229                                       & iter->image->geometry, &iter->xdr[iter->level],
1230                                       iter->level ? get_UINT16BE(iter->xdr[iter->level-1].fdr.prs)
1231                                                : get_UINT16BE(iter->image->sec0.vpl))))
1232         && (iter->xdr[iter->level].fdr.fnm[0] == 0))
1233   {
1234      iter->index[iter->level]++;
1235      while (iter->index[iter->level] >= iter->nrc[iter->level])
1236         iter->level--;
1237   }
1238
1239   if (iter->level < 0)
1240   {
1241      ent->eof = 1;
1242   }
1243   else if (reply)
1244      return IMGTOOLERR_READERROR;
1245   else
1246   {
1247#if 0
1248      fname_to_str(ent->filename, iter->xdr[iter->level].fdr.fnm, sizeof(ent->filename) / sizeof(ent->filename[0]));
1249#else
1250      {
1251         int i;
1252         char buf[9];
1253
1254         ent->filename[0] = '\0';
1255         for (i=0; i<iter->level; i++)
1256         {
1257            fname_to_str(buf, iter->xdr[i].fdr.fnm, 9);
1258            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
1259            strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
1260         }
1261         fname_to_str(buf, iter->xdr[iter->level].fdr.fnm, 9);
1262         strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
1263      }
1264#endif
1265
1266      /* parse flags */
1267      flag = get_UINT16BE(iter->xdr[iter->level].fdr.flg);
1268      if (flag & fdr_flg_cdr)
1269      {
1270         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "CHANNEL");
1271
1272         ent->filesize = 0;
1273      }
1274      else if (flag & fdr_flg_ali)
1275      {
1276         ti990_fdr target_fdr;
1277         char buf[9];
1278
1279         reply = read_sector_logical_len(iter->image->file_handle,
1280                                    iter->level ? ((unsigned) get_UINT16BE(iter->xdr[iter->level-1].fdr.paa) * get_UINT16BE(iter->image->sec0.spa) + get_UINT16BE(iter->xdr[iter->level].adr.raf))
1281                                             : ((unsigned) get_UINT16BE(iter->image->sec0.vda) * get_UINT16BE(iter->image->sec0.spa) + get_UINT16BE(iter->xdr[iter->level].adr.raf)),
1282                                    & iter->image->geometry, &target_fdr,
1283                                    iter->level ? get_UINT16BE(iter->xdr[iter->level-1].fdr.prs)
1284                                             : get_UINT16BE(iter->image->sec0.vpl));
1285
1286         fname_to_str(buf, target_fdr.fnm, 9);
1287
1288         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "ALIAS OF %s", buf);
1289
1290         ent->filesize = 0;
1291      }
1292      else
1293      {
1294         const char *fmt, *type;
1295
1296         switch ((flag >> fdr_flg_fmt_shift) & 3)
1297         {
1298         case 0:
1299            fmt = "NBS";
1300            break;
1301         case 1:
1302            fmt = "BS ";
1303            break;
1304         default:
1305            fmt = "???";
1306            break;
1307         }
1308
1309         switch ((flag >> fdr_flg_fu_shift) & 3)
1310         {
1311         case 1:
1312            type = "DIR";
1313            break;
1314         case 2:
1315            type = "PRO";
1316            break;
1317         case 3:
1318            type = "IMG";
1319            break;
1320         default:
1321            switch ((flag >> fdr_flg_ft_shift) & 3)
1322            {
1323            case 1:
1324               type = "SEQ";
1325               break;
1326            case 2:
1327               type = "REL";
1328               break;
1329            case 3:
1330               type = "KIF";
1331               break;
1332            default:
1333               type = "???";
1334               break;
1335            }
1336            break;
1337         }
1338         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]),
1339                  "%s %c %s%s%s%s%s", fmt, (flag & fdr_flg_all) ? 'N' : 'C', type,
1340                     (flag & fdr_flg_blb) ? "" : " BLK",
1341                     (flag & fdr_flg_tmp) ? " TMP" : "",
1342                     (flag & fdr_flg_wpb) ? " WPT" : "",
1343                     (flag & fdr_flg_dpb) ? " DPT" : "");
1344
1345         /* len in blocks */
1346         ent->filesize = get_UINT32BE(iter->xdr[iter->level].fdr.bkm);
1347         if ((((flag >> fdr_flg_ft_shift) & 3) == 3) || get_UINT16BE(iter->xdr[iter->level].fdr.ofm))
1348            ent->filesize++;
1349
1350         /* convert to ADUs */
1351         if (iter->xdr[iter->level].fdr.apb > 1)
1352            /* more than one ADU per block */
1353            ent->filesize *= iter->xdr[iter->level].fdr.apb;
1354         else if (iter->xdr[iter->level].fdr.bpa > 1)
1355            /* more than one block per ADU */
1356            ent->filesize = (ent->filesize + iter->xdr[iter->level].fdr.bpa - 1) / iter->xdr[iter->level].fdr.bpa;
1357      }
1358      iter->index[iter->level]++;
1359
1360      if (get_UINT16BE(iter->xdr[iter->level].fdr.saa) != 0)
1361         printf("roupoupou");
1362      else
1363      {
1364         int i;
1365         for (i=0; i<64; i++)
1366            if (iter->xdr[iter->level].fdr.sat[i])
1367            {
1368               printf("roupoupou");
1369               break;
1370            }
1371      }
1372
1373      /* recurse subdirectory if applicable */
1374      if ((((flag >> fdr_flg_fu_shift) & 3) == 1)
1375         && (! (flag & fdr_flg_ali))
1376         && (! (flag & fdr_flg_cdr))
1377         && (iter->level < MAX_DIR_LEVEL)
1378         && ! ((iter->level == 0) && ! memcmp(iter->xdr[iter->level].fdr.fnm, "VCATALOG", 8)))
1379      {
1380         ti990_dor dor;
1381
1382         if (get_UINT16BE(iter->xdr[iter->level].fdr.saa) != 0)
1383            printf("ninou");
1384
1385         read_sector_logical_len(iter->image->file_handle,
1386                           get_UINT16BE(iter->xdr[iter->level].fdr.paa) * get_UINT16BE(iter->image->sec0.spa),
1387                           & iter->image->geometry, &dor, sizeof(dor));
1388
1389         iter->level++;
1390         iter->nrc[iter->level] = get_UINT16BE(dor.nrc)/*get_UINT32BE(iter->fdr[iter->level-1].eom)-1*/;
1391         iter->index[iter->level] = 0;
1392         /*if (get_UINT16BE(dor.nrc) != (get_UINT32BE(iter->xdr[iter->level-1].fdr.eom)-1))
1393            printf("hiha");*/
1394      }
1395
1396      /* go to upper level if applicable */
1397      while (iter->index[iter->level] >= iter->nrc[iter->level])
1398         iter->level--;
1399   }
1400
1401   return 0;
1402}
1403
1404/*
1405   Free enumerator
1406*/
1407static void ti990_image_closeenum(imgtool_directory *enumeration)
1408{
1409}
1410
1411/*
1412   Compute free space on disk image (in ADUs)
1413*/
1414static imgtoolerr_t ti990_image_freespace(imgtool_partition *partition, UINT64 *size)
1415{
1416   imgtool_image *img = imgtool_partition_image(partition);
1417   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1418   int totadus = get_UINT16BE(image->sec0.tna);
1419   int adu, record, sub_adu;
1420   char buf[256];
1421   size_t freeadus = 0;
1422
1423   if ((totadus+2031)/2032 != image->sec0.tbm)
1424      /*return IMGTOOLERR_CORRUPTIMAGE;*/
1425      return 0;
1426
1427   adu = 0;
1428   record = 0;
1429   sub_adu = 0;
1430   while (adu<totadus)
1431   {
1432      read_sector_logical_len(image->file_handle, image->sec0.sbm + record, &image->geometry, buf, sizeof(buf));
1433
1434      while ((adu < totadus) && (sub_adu < 2032))
1435      {
1436         if (! (buf[(sub_adu >> 3) + 2] & (1 << (sub_adu & 7))))
1437            freeadus++;
1438         sub_adu++;
1439         adu++;
1440      }
1441      sub_adu = 0;
1442      record++;
1443   }
1444
1445   * size = freeadus;
1446
1447   return IMGTOOLERR_SUCCESS;
1448}
1449
1450#ifdef UNUSED_FUNCTION
1451/*
1452   Extract a file from a ti990_image.
1453*/
1454static imgtoolerr_t ti990_image_readfile(imgtool_partition *partition, const char *fpath, imgtool_stream *destf)
1455{
1456   imgtool_image *img = imgtool_partition_image(partition);
1457   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1458   int catalog_index, fdr_secnum, parent_fdr_secnum;
1459   imgtoolerr_t reply;
1460
1461
1462   reply = find_fdr(image, fpath, &catalog_index, &fdr_secnum, &parent_fdr_secnum);
1463   if (reply)
1464      return reply;
1465
1466   /* ... */
1467
1468   return 0;
1469
1470#if 0
1471   ti99_image *image = (ti99_image*) img;
1472   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
1473   char ti_fname[10];
1474   ti99_fdr fdr;
1475   tifile_header dst_header;
1476   int i, lnks_index;
1477   int cur_sec, last_sec;
1478   int secsused;
1479   UINT8 buf[256];
1480   int reply;
1481
1482   str_to_fname(ti_fname, filename);
1483
1484   reply = find_fdr(image, ti_fname, &fdr, NULL);
1485   if (reply)
1486      return reply;
1487
1488   dst_header.tifiles[0] = '\7';
1489   dst_header.tifiles[1] = 'T';
1490   dst_header.tifiles[2] = 'I';
1491   dst_header.tifiles[3] = 'F';
1492   dst_header.tifiles[4] = 'I';
1493   dst_header.tifiles[5] = 'L';
1494   dst_header.tifiles[6] = 'E';
1495   dst_header.tifiles[7] = 'S';
1496   dst_header.secsused_MSB = fdr.secsused_MSB;
1497   dst_header.secsused_LSB = fdr.secsused_LSB;
1498   dst_header.flags = fdr.flags;
1499   dst_header.recspersec = fdr.recspersec;
1500   dst_header.eof = fdr.eof;
1501   dst_header.reclen = fdr.reclen;
1502   dst_header.fixrecs_MSB = fdr.fixrecs_MSB;
1503   dst_header.fixrecs_LSB = fdr.fixrecs_LSB;
1504   for (i=0; i<(128-14); i++)
1505      dst_header.res[i] = 0;
1506
1507   if (stream_write(destf, & dst_header, 128) != 128)
1508      return IMGTOOLERR_WRITEERROR;
1509
1510
1511   secsused = get_fdr_secsused(&fdr);
1512
1513   i = 0;         /* file logical sector #0 */
1514   lnks_index = 0;   /* start of file block table */
1515   while (i<secsused)
1516   {
1517      if (lnks_index == 76)
1518         return IMGTOOLERR_CORRUPTIMAGE;
1519
1520      /* read curent file block table entry */
1521      cur_sec = ((fdr.lnks[lnks_index][1] & 0xf) << 8) | fdr.lnks[lnks_index][0];
1522      last_sec = (fdr.lnks[lnks_index][2] << 4) | (fdr.lnks[lnks_index][1] >> 4);
1523
1524      /* copy current file block */
1525      while ((i<=last_sec) && (i<secsused))
1526      {
1527         if (cur_sec >= totsecs)
1528            return IMGTOOLERR_CORRUPTIMAGE;
1529
1530         if (read_sector_logical(image->file_handle, cur_sec, & image->geometry, buf))
1531            return IMGTOOLERR_READERROR;
1532
1533         if (stream_write(destf, buf, 256) != 256)
1534            return IMGTOOLERR_WRITEERROR;
1535
1536         i++;
1537         cur_sec++;
1538      }
1539
1540      /* next entry in file block table */
1541      lnks_index++;
1542   }
1543#endif
1544
1545   return 0;
1546}
1547
1548/*
1549   Add a file to a ti990_image.
1550*/
1551static imgtoolerr_t ti990_image_writefile(imgtool_partition *partition, const char *fpath, imgtool_stream *sourcef, option_resolution *writeoptions)
1552{
1553   imgtool_image *img = imgtool_partition_image(partition);
1554   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1555   int catalog_index, fdr_secnum, parent_fdr_secnum;
1556   imgtoolerr_t reply;
1557
1558
1559   /* check that file does not exist */
1560   reply = find_fdr(image, fpath, &catalog_index, &fdr_secnum, &parent_fdr_secnum);
1561   if ((reply) && (reply != IMGTOOLERR_FILENOTFOUND))
1562      return reply;
1563
1564   /* ... */
1565
1566   return 0;
1567
1568#if 0
1569   ti99_image *image = (ti99_image*) img;
1570   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
1571   char ti_fname[10];
1572   ti99_fdr fdr;
1573   tifile_header src_header;
1574   int i, lnks_index;
1575   int cur_sec, last_sec;
1576   int secsused;
1577   UINT8 buf[256];
1578   int reply;
1579   int fdr_secnum;
1580
1581   str_to_fname(ti_fname, filename);
1582
1583   reply = find_fdr(image, ti_fname, &fdr, NULL);
1584   if (reply == 0)
1585   {   /* file already exists: causes an error for now */
1586      return IMGTOOLERR_UNEXPECTED;
1587   }
1588   else if (reply != IMGTOOLERR_FILENOTFOUND)
1589   {
1590      return reply;
1591   }
1592
1593   if (stream_read(sourcef, & src_header, 128) != 128)
1594      return IMGTOOLERR_READERROR;
1595
1596   /* create new file */
1597   reply = new_file(image, ti_fname, &fdr_secnum);
1598   if (reply)
1599      return reply;
1600
1601   memcpy(fdr.name, ti_fname, 10);
1602   fdr.res10[1] = fdr.res10[0] = 0;
1603   fdr.flags = src_header.flags;
1604   fdr.recspersec = src_header.recspersec;
1605   fdr.secsused_MSB = /*src_header.secsused_MSB*/0;
1606   fdr.secsused_LSB = /*src_header.secsused_LSB*/0;
1607   fdr.eof = src_header.eof;
1608   fdr.reclen = src_header.reclen;
1609   fdr.fixrecs_LSB = src_header.fixrecs_LSB;
1610   fdr.fixrecs_MSB = src_header.fixrecs_MSB;
1611   for (i=0; i<8; i++)
1612      fdr.res20[i] = 0;
1613   for (i=0; i<76; i++)
1614      fdr.lnks[i][2] = fdr.lnks[i][1] = fdr.lnks[i][0] = 0;
1615
1616   /* alloc data sectors */
1617   secsused = (src_header.secsused_MSB << 8) | src_header.secsused_LSB;
1618   reply = alloc_file_sectors(image, &fdr, secsused);
1619   if (reply)
1620      return reply;
1621
1622   /* copy data */
1623   i = 0;
1624   lnks_index = 0;
1625   while (i<secsused)
1626   {
1627      if (lnks_index == 76)
1628         return IMGTOOLERR_CORRUPTIMAGE;
1629
1630      cur_sec = ((fdr.lnks[lnks_index][1] & 0xf) << 8) | fdr.lnks[lnks_index][0];
1631      last_sec = (fdr.lnks[lnks_index][2] << 4) | (fdr.lnks[lnks_index][1] >> 4);
1632
1633      while ((i<secsused) && (i<=last_sec))
1634      {
1635         if (cur_sec >= totsecs)
1636            return IMGTOOLERR_CORRUPTIMAGE;
1637
1638         if (stream_read(sourcef, buf, 256) != 256)
1639            return IMGTOOLERR_READERROR;
1640
1641         if (write_sector_logical(image->file_handle, cur_sec, & image->geometry, buf))
1642            return IMGTOOLERR_WRITEERROR;
1643
1644         i++;
1645         cur_sec++;
1646      }
1647
1648      lnks_index++;
1649   }
1650
1651   /* write fdr */
1652   if (write_sector_logical(image->file_handle, fdr_secnum, & image->geometry, &fdr))
1653      return IMGTOOLERR_WRITEERROR;
1654
1655   /* update catalog */
1656   for (i=0; i<128; i++)
1657   {
1658      buf[2*i] = image->catalog[i].fdr_secnum >> 8;
1659      buf[2*i+1] = image->catalog[i].fdr_secnum & 0xff;
1660   }
1661   if (write_sector_logical(image->file_handle, 1, & image->geometry, buf))
1662      return IMGTOOLERR_WRITEERROR;
1663
1664   /* update bitmap */
1665   if (write_sector_logical(image->file_handle, 0, & image->geometry, &image->sec0))
1666      return IMGTOOLERR_WRITEERROR;
1667#endif
1668
1669   return 0;
1670}
1671
1672/*
1673   Delete a file from a ti990_image.
1674*/
1675static imgtoolerr_t ti990_image_deletefile(imgtool_partition *partition, const char *fpath)
1676{
1677   imgtool_image *img = imgtool_partition_image(partition);
1678   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1679   int catalog_index, fdr_secnum, parent_fdr_secnum;
1680   imgtoolerr_t reply;
1681
1682
1683   reply = find_fdr(image, fpath, &catalog_index, &fdr_secnum, &parent_fdr_secnum);
1684   if (reply)
1685      return reply;
1686
1687   /* ... */
1688
1689   return 0;
1690
1691#if 0
1692   ti99_image *image = (ti99_image*) img;
1693   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
1694   char ti_fname[10];
1695   ti99_fdr fdr;
1696   int i, lnks_index;
1697   int cur_sec, last_sec;
1698   int secsused;
1699   int catalog_index;
1700   int reply;
1701   UINT8 buf[256];
1702
1703   str_to_fname(ti_fname, filename);
1704
1705   reply = find_fdr(image, ti_fname, &fdr, &catalog_index);
1706   if (reply)
1707      return reply;
1708
1709   /* free data sectors */
1710   secsused = get_fdr_secsused(&fdr);
1711
1712   i = 0;
1713   lnks_index = 0;
1714   while (i<secsused)
1715   {
1716      if (lnks_index == 76)
1717         return IMGTOOLERR_CORRUPTIMAGE;
1718
1719      cur_sec = ((fdr.lnks[lnks_index][1] & 0xf) << 8) | fdr.lnks[lnks_index][0];
1720      last_sec = (fdr.lnks[lnks_index][2] << 4) | (fdr.lnks[lnks_index][1] >> 4);
1721
1722      while ((i<secsused) && (i<=last_sec))
1723      {
1724         if (cur_sec >= totsecs)
1725            return IMGTOOLERR_CORRUPTIMAGE;
1726
1727         image->sec0.abm[cur_sec >> 3] &= ~ (1 << (cur_sec & 7));
1728
1729         i++;
1730         cur_sec++;
1731      }
1732
1733      lnks_index++;
1734   }
1735
1736   /* free fdr sector */
1737   image->sec0.abm[image->catalog[catalog_index].fdr_secnum >> 3] &= ~ (1 << (image->catalog[catalog_index].fdr_secnum & 7));
1738
1739   /* delete catalog entry */
1740   for (i=catalog_index; i<127; i++)
1741      image->catalog[i] = image->catalog[i+1];
1742   image->catalog[127].fdr_secnum = 0;
1743
1744   /* update catalog */
1745   for (i=0; i<128; i++)
1746   {
1747      buf[2*i] = image->catalog[i].fdr_secnum >> 8;
1748      buf[2*i+1] = image->catalog[i].fdr_secnum & 0xff;
1749   }
1750   if (write_sector_logical(image->file_handle, 1, & image->geometry, buf))
1751      return IMGTOOLERR_WRITEERROR;
1752
1753   /* update bitmap */
1754   if (write_sector_logical(image->file_handle, 0, & image->geometry, &image->sec0))
1755      return IMGTOOLERR_WRITEERROR;
1756#endif
1757
1758   return 0;
1759}
1760#endif
1761
1762/*
1763   Create a blank ti990_image.
1764*/
1765static imgtoolerr_t ti990_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions)
1766{
1767   //const char *volname;
1768   ti990_geometry geometry;
1769   unsigned totsecs;
1770   disk_image_header header;
1771   ti990_sc0 sec0;
1772   UINT8 empty_sec[MAX_SECTOR_SIZE];
1773   int reply;
1774   int i;
1775
1776   /* read options */
1777   //volname = option_resolution_lookup_string(createoptions, ti990_createopts_volname);
1778   geometry.cylinders = option_resolution_lookup_int(createoptions, ti990_createopts_cylinders);
1779   geometry.heads = option_resolution_lookup_int(createoptions, ti990_createopts_heads);
1780   geometry.sectors_per_track = option_resolution_lookup_int(createoptions, ti990_createopts_sectors);
1781   geometry.bytes_per_sector = option_resolution_lookup_int(createoptions, ti990_createopts_sectorsize);
1782
1783   totsecs = geometry.cylinders * geometry.heads * geometry.sectors_per_track;
1784
1785   /* write header */
1786   set_UINT32BE(& header.cylinders, geometry.cylinders);
1787   set_UINT32BE(& header.heads, geometry.heads);
1788   set_UINT32BE(& header.sectors_per_track, geometry.sectors_per_track);
1789   set_UINT32BE(& header.bytes_per_sector, geometry.bytes_per_sector);
1790
1791   reply = stream_write(f, &header, sizeof(header));
1792   if (reply != sizeof(header))
1793   {
1794      return IMGTOOLERR_WRITEERROR;
1795   }
1796
1797
1798   /* initialize sector 0 */
1799   /* mark disk as uninitialized */
1800   set_UINT16BE(& sec0.sta, 2);
1801
1802
1803   /* write sector 0 */
1804   if (write_sector_logical(f, 0, & geometry, &sec0))
1805      return IMGTOOLERR_WRITEERROR;
1806
1807
1808   /* now clear every other sector, including catalog */
1809   memset(empty_sec, 0, geometry.bytes_per_sector);
1810
1811   for (i=1; i<totsecs; i++)
1812      if (write_sector_logical(f, i, & geometry, empty_sec))
1813         return IMGTOOLERR_WRITEERROR;
1814
1815   return 0;
1816}
src/mess/tools/imgtool/d64.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include <assert.h>
5#include "osdepend.h"
6#include "imgtoolx.h"
7#include "d64.h"
8
9#ifdef LSB_FIRST
10typedef UINT16 littleuword;
11#define GET_UWORD(a) a
12#define SET_UWORD(a,v) a=v
13#else
14typedef struct {
15   unsigned char low, high;
16} littleuword;
17#define GET_UWORD(a) (a.low|(a.high<<8))
18#define SET_UWORD(a,v) a.low=(v)&0xff;a.high=((v)>>8)&0xff
19#endif
20
21/* tracks 1 to 35
22 * sectors number from 0
23 * each sector holds 256 data bytes
24 * directory and Bitmap Allocation Memory in track 18
25 * sector 0:
26 * 0: track# of directory begin (this linkage of sector often used)
27 * 1: sector# of directory begin
28 *
29 * BAM entries (one per track)
30 * offset 0: # of free sectors
31 * offset 1: sector 0 (lsb) free to sector 7
32 * offset 2: sector 8 to 15
33 * offset 3: sector 16 to whatever the number to sectors in track is
34 *
35 * directory sector:
36 * 0,1: track sector of next directory sector
37 * 2, 34, 66, ... : 8 directory entries
38 *
39 * directory entry:
40 * 0: file type
41 * (0x = scratched/splat, 8x = alive, Cx = locked
42 * where x: 0=DEL, 1=SEQ, 2=PRG, 3=USR, 4=REL)
43 * 1,2: track and sector of file
44 * 3..18: file name padded with a0
45 * 19,20: REL files side sector
46 * 21: REL files record length
47 * 28,29: number of blocks in file
48 * ended with illegal track and sector numbers
49 */
50
51// x64 d64 image with 64 byte header
52
53#define D64_MAX_TRACKS 40
54
55static int d64_sectors_per_track[] =
56{
57   21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
58   19, 19, 19, 19, 19, 19, 19,
59   18, 18, 18, 18, 18, 18,
60   17, 17, 17, 17, 17,
61   17, 17, 17, 17, 17 // non standard
62};
63
64static int d64_offset[D64_MAX_TRACKS+1];         /* offset of begin of track in d64 file */
65
66typedef struct {
67   unsigned char track, sector, // of next directory
68      format, doublesided;
69   struct { unsigned char free, map[3]; } bam[35];
70   unsigned char name[0x10], filler[2], id[2], filler2, version[2], filler3[4];
71   unsigned char unused[50]; // zero
72   unsigned char free2[35]; //freecount for 1751 tracks 36..70
73} D64_HEADER;
74
75typedef struct {
76   unsigned char unused[0x6a]; // zero
77   struct { unsigned char map2[3]; } bam2[35];
78   unsigned char unused2[0x2d]; // zer0
79} D71_HEADER;
80
81static D64_HEADER d64_header={
82   18,1,'A',
83   0, // 1571 0x80
84   { { 0 } },
85   { '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0',
86     '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0' },
87   { 0xa0, 0xa0 }, { 0xa0, 0xa0 } , 0xa0, { '2', 'A' } , { '\xa0','\xa0','\xa0','\xa0' },
88};
89
90typedef struct {
91   unsigned char not_usable[2];
92   unsigned char type;
93#define FILE_TYPE_DEL 0
94#define FILE_TYPE_SEQ 1
95#define FILE_TYPE_PRG 2
96#define FILE_TYPE_USR 3
97#define FILE_TYPE_REL 4
98#define FILE_TYPE_MASK 0x3f
99   unsigned char track, sector, name[0x10];
100   unsigned char rel_track, rel_sector, rel_length;
101   unsigned char unused[4];
102   unsigned char replace_track, replace_sector;
103   littleuword blocks;
104} D64_ENTRY;
105
106typedef union {
107   struct {
108      unsigned char track, sector; //linkage to next track=0 for last
109   } linkage;
110   D64_ENTRY entry[8];
111} D64_DIRECTORY;
112
113typedef struct {
114   unsigned char track, sector, // of next directory
115      format, unused;
116   unsigned char name[0x12], id[2], filler2, version[2], filler3[2];
117   unsigned char unused1[227]; // zero
118} D81_HEADER;
119
120static D81_HEADER d81_header={
121   40,3,'D',
122   0,
123   { '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0',
124     '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0', 0xa0, 0xa0 },
125   { 0xa0, 0xa0 } , 0xa0, { '3', 'D' } , { '\xa0','\xa0' },
126};
127
128typedef struct {
129   unsigned char track, sector;
130   unsigned char version, complement;
131   unsigned char id[2], iobyte, autoloader;
132   unsigned char reserved[8];
133   struct { unsigned char free, map[5]; } bam[40];
134} D81_BAM;
135
136static D81_BAM d81_bam={
137   40, 2,0x44, 0xbb,
138};
139
140#define D71_MAX_TRACKS 70
141
142int d71_sectors_per_track[] =
143{
144   21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
145   19, 19, 19, 19, 19, 19, 19,
146   18, 18, 18, 18, 18, 18,
147   17, 17, 17, 17, 17,
148   21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
149   19, 19, 19, 19, 19, 19, 19,
150   18, 18, 18, 18, 18, 18,
151   17, 17, 17, 17, 17
152};
153
154static int d71_offset[D71_MAX_TRACKS+1];         /* offset of begin of track in d64 file */
155
156/* must be called before other functions */
157void d64_open_helper (void)
158{
159   int i;
160
161   d64_offset[0] = 0;
162   for (i = 1; i <= D64_MAX_TRACKS; i++)
163      d64_offset[i] = d64_offset[i - 1] + d64_sectors_per_track[i - 1] * 256;
164
165   d71_offset[0] = 0;
166   for (i = 1; i <= D71_MAX_TRACKS; i++)
167      d71_offset[i] = d71_offset[i - 1] + d71_sectors_per_track[i - 1] * 256;
168}
169
170/* calculates offset to beginning of d64 file for sector beginning */
171static int d64_tracksector2offset (int track, int sector)
172{
173   return d64_offset[track - 1] + sector * 256;
174}
175
176/* calculates offset to beginning of d71 file for sector beginning */
177int d71_tracksector2offset (int track, int sector)
178{
179   return d71_offset[track - 1] + sector * 256;
180}
181
182/* calculates offset to beginning of d71 file for sector beginning */
183int d81_tracksector2offset (int track, int sector)
184{
185   return ((track - 1)*20*2 + sector )* 256;
186}
187
188static void cbm_filename_to_cstring(unsigned char *cbmstring, int size, unsigned char* cstring)
189{
190   int i;
191   for (i=0; (i<size)&&(cbmstring[i]!=0xa0); i++) cstring[i]=cbmstring[i];
192   cstring[i]=0;
193}
194
195int cbm_compareNames (const unsigned char *left, const unsigned char *right)
196{
197   int i;
198
199   for (i = 0; i < 16; i++)
200   {
201      if ((left[i] == '*') || (right[i] == '*'))
202         return 1;
203
204      if (left[i] == right[i]) {
205         if (left[i]==0) return 1;
206         continue;
207      }
208      if ((left[i] == 0xa0) && (right[i] == 0))
209         return 1;
210      if ((right[i] == 0xa0) && (left[i] == 0))
211         return 1;
212      return 0;
213   }
214   return 1;
215}
216
217typedef struct _d64_image {
218   imgtool_image base;
219   imgtool_stream *file_handle;
220   int d64;
221   int x64; // x64 header at the beginning
222   int d71; // c128d/1571 diskette
223   int d81; // c65/1581/1565 diskette
224
225   int (*get_offset)(int track, int sector);
226   void (*alloc_sector)(struct _d64_image *image, int *track, int *sector);
227   void (*free_sector)(struct _d64_image *image, int track, int sector);
228   struct { int track, sector; } directory;
229   int bam_bytes_dir_track;
230
231   int tracks; //35 or 40 tracks
232   int crc; // crc data at the end of file
233   int size;
234   int modified;
235   unsigned char *realimage; //inclusive x64 header
236   unsigned char *data; // pointer to start of d64 image
237} d64_image;
238
239typedef struct {
240   imgtool_directory base;
241   d64_image *image;
242   int track, sector;
243   int offset;
244} d64_iterator;
245
246static void d64_alloc_sector(struct _d64_image *image, int *track, int *sector)
247{
248   static int tracks[35];
249   int i, j;
250   D64_HEADER *header=(D64_HEADER*)
251      (image->data+image->get_offset(image->directory.track,image->directory.sector));
252
253   // this contains the tracks for the search strategy for free sectors
254   for (i=0,j=17; i<35; i+=2,j--) tracks[i]=j;
255   for (i=1,j=19; i<35; i+=2,j++) tracks[i]=j;
256   tracks[35-1]=18;
257
258   for (i=0; i<35; i++) {
259      *track=tracks[i];
260      if (header->bam[*track-1].free) {
261         for (j=0,*sector=0;j<3; j++) {
262            int mask=1;
263            for (; mask<=0x80; mask<<=1, (*sector)++) {
264               if (header->bam[*track-1].map[j]&mask) {
265                  header->bam[*track-1].map[j]&=~mask;
266                  header->bam[*track-1].free--;
267                  return;
268               }
269            }
270         }
271      }
272   }
273}
274
275static void d64_free_sector(struct _d64_image *image, int track, int sector)
276{
277   D64_HEADER *header=(D64_HEADER*)
278      (image->data+image->get_offset(image->directory.track,image->directory.sector));
279   int i=sector>>3;
280   int mask=1<<(sector&7);
281   header->bam[track-1].free++;
282   header->bam[track-1].map[i]|=mask;
283}
284
285static void d71_alloc_sector(struct _d64_image *image, int *track, int *sector)
286{
287   static int tracks[70];
288   int i, j;
289   D64_HEADER *header=(D64_HEADER*)
290      (image->data+image->get_offset(image->directory.track,image->directory.sector));
291   D71_HEADER *header2=(D71_HEADER*)
292      (image->data+image->get_offset(image->directory.track+35,image->directory.sector));
293
294   // this contains the tracks for the search strategy for free sectors
295   for (i=0,j=17; i<35; i+=4,j--) { tracks[i]=j; tracks[i+1]=j+35; }
296   for (i=2,j=19; i<35; i+=4,j++) { tracks[i]=j; tracks[i+1]=j+35; }
297   tracks[70-1]=18;
298
299   for (i=0; i<35; i++) {
300      *track=tracks[i];
301      if (*tracks<=35) {
302         if (header->bam[*track-1].free) {
303            for (j=0,*sector=0;j<3; j++) {
304               int mask=1;
305               for (; mask<=0x80; mask<<=1, (*sector)++) {
306                  if (header->bam[*track-1].map[j]&mask) {
307                     header->bam[*track-1].map[j]&=~mask;
308                     header->bam[*track-1].free--;
309                     return;
310                  }
311               }
312            }
313         }
314      } else {
315         if (header->free2[*track-36]) {
316            for (j=0,*sector=0;j<3; j++) {
317               int mask=1;
318               for (; mask<=0x80; mask<<=1, (*sector)++) {
319                  if (header2->bam2[*track-36].map2[j]&mask) {
320                     header2->bam2[*track-36].map2[j]&=~mask;
321                     header->free2[*track-36]--;
322                     return;
323                  }
324               }
325            }
326         }
327      }
328   }
329}
330
331static void d71_free_sector(struct _d64_image *image, int track, int sector)
332{
333   D64_HEADER *header=(D64_HEADER*)
334      (image->data+image->get_offset(image->directory.track,image->directory.sector));
335   D71_HEADER *header2=(D71_HEADER*)
336      (image->data+image->get_offset(image->directory.track+35,image->directory.sector));
337   int i=sector>>3;
338   int mask=1<<(sector&7);
339   if (track<=35) {
340      header->bam[track-1].free++;
341      header->bam[track-1].map[i]|=mask;
342   } else {
343      header->free2[track-36]++;
344      header2->bam2[track-36].map2[i]|=mask;
345   }
346}
347
348static void d81_alloc_sector(struct _d64_image *image, int *track, int *sector)
349{
350   static int tracks[80];
351   int i, j;
352   D81_BAM *bam[2];
353   bam[0] = (D81_BAM*) (image->data + image->get_offset(image->directory.track, image->directory.sector+1)),
354   bam[1] = (D81_BAM*) (image->data + image->get_offset(image->directory.track, image->directory.sector+1));
355   
356   /* this contains the tracks for the search strategy for free sectors */
357   for (i=0,j=image->directory.track-1; j>0; i++,j--) tracks[i]=j;
358   for (j=image->directory.track+1;j<80;i++,j++) tracks[i]=j;
359   tracks[i]=image->directory.track;
360
361   for (i=0; i<80; i++) {
362      D81_BAM *b;
363      *track=tracks[i];
364      if (*track<=40) b=bam[0];
365      else b=bam[1];
366      if (b->bam[*track-1].free) {
367         for (j=0,*sector=0;j<6; j++) {
368            int mask=0;
369            for (; mask<=0x80; mask<<=1, (*sector)++) {
370               if (b->bam[*track-1].map[j]&mask) {
371                  b->bam[*track-1].map[j]&=~mask;
372                  b->bam[*track-1].free--;
373                  return;
374               }
375            }
376         }
377      }
378   }
379}
380
381static void d81_free_sector(struct _d64_image *image, int track, int sector)
382{
383   D81_BAM *bam;
384   int i=sector>>3;
385   int mask=1<<(sector&7);
386
387   if (track<=40) {
388      bam=(D81_BAM*)
389         (image->data
390          +image->get_offset(image->directory.track,
391                        image->directory.sector+1));
392   } else {
393      track-=40;
394      bam=(D81_BAM*)
395         (image->data
396          +image->get_offset(image->directory.track,
397                        image->directory.sector+2));
398   }
399   
400   bam->bam[track-1].free++;
401   bam->bam[track-1].map[i]|=mask;
402}
403
404int d64_getcrc(d64_image *image, int track, int sector)
405{
406   int pos=d64_tracksector2offset(track, sector)>>8;
407   if (!image->crc) return 0;
408   return image->data[d64_tracksector2offset(image->tracks+1,0)+pos];
409}
410
411static D64_ENTRY *d64_get_free_entry(d64_image *image)
412{
413   D64_HEADER *header;
414   D64_DIRECTORY *dir = (D64_DIRECTORY*)
415      (image->data+image->get_offset (image->directory.track, image->directory.sector));
416
417   int i, mask, s;
418
419   while ((dir->linkage.track >= 1) && (dir->linkage.track <= image->tracks))
420   {
421      dir=(D64_DIRECTORY*)
422         (image->data+image->get_offset(dir->linkage.track, dir->linkage.sector));
423      for (i = 0; i < 8; i ++)
424      {
425         if (!(dir->entry[i].type & 0x80))
426            return dir->entry + i;
427      }
428   }
429
430   // add new sector to directory
431    header = (D64_HEADER*)
432      (image->data+image->get_offset (image->directory.track, image->directory.sector));
433
434   if (header->bam[image->directory.track-1].free) {
435      for (i=0, s=0; i<image->bam_bytes_dir_track; i++) {
436         for (mask=0x80; mask>0; mask>>=1, s++) {
437            if (header->bam[image->directory.track-1].map[i]&mask) {
438               header->bam[image->directory.track-1].free--;
439               header->bam[image->directory.track-1].map[i]&=~mask;
440               dir->linkage.track=image->directory.track-1;
441               dir->linkage.sector=s;
442               return (D64_ENTRY*)(image->data+image->get_offset(image->directory.track, s));
443            }
444         }
445      }
446   }
447   // no sector in directory track free
448   return NULL;
449}
450
451/* searches program with given name in directory */
452static D64_ENTRY *d64_image_findfile (d64_image *image, const unsigned char *name)
453{
454   int i;
455
456   D64_DIRECTORY *dir = (D64_DIRECTORY*)
457      (image->data+image->get_offset (image->directory.track, image->directory.sector));
458
459   while ((dir->linkage.track >= 1) && (dir->linkage.track <= image->tracks))
460   {
461      dir=(D64_DIRECTORY*)
462         (image->data+image->get_offset(dir->linkage.track, dir->linkage.sector));
463      for (i = 0; i < 8; i ++)
464      {
465         if (dir->entry[i].type & 0x80)
466         {
467            if (mame_stricmp ((char *) name, (char *) "*") == 0)
468               return dir->entry + i;
469            if (cbm_compareNames (name, dir->entry[i].name))
470               return dir->entry + i;
471         }
472      }
473   }
474   return NULL;
475}
476
477#if 0
478static int d64_filesize(d64_image *image, D64_ENTRY *entry)
479{
480   int size = 0;
481   int i=image->get_offset(entry->track, entry->sector);
482   
483   while (image->data[i] != 0)
484   {
485      size += 254;
486      i = image->get_offset (image->data[i], image->data[i + 1]);
487   }
488   size += image->data[i + 1]-1;
489   return size;
490}
491#endif
492
493static int d64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
494static void d64_image_exit(imgtool_image *img);
495static void d64_image_info(imgtool_image *img, char *string, const int len);
496static int d64_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
497static int d64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
498static void d64_image_closeenum(imgtool_directory *enumeration);
499static size_t d64_image_freespace(imgtool_image *img);
500static int d64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
501static int d64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
502static int d64_image_deletefile(imgtool_image *img, const char *fname);
503static int d64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
504
505static int x64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
506static int x64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
507
508static int d71_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
509static size_t d71_image_freespace(imgtool_image *img);
510static int d71_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
511
512static int d81_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
513static void d81_image_info(imgtool_image *img, char *string, const int len);
514static size_t d81_image_freespace(imgtool_image *img);
515static int d81_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
516
517static int d64_read_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, void *buffer, int length);
518static int d64_write_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, const void *buffer, int length);
519
520static struct OptionTemplate d64_createopts[] =
521{
522   { "label",   NULL, IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,   0,      0,      NULL   },   /* [3] */
523   { NULL, NULL, 0, 0, 0, 0 }
524};
525
526#define D64_CREATEOPTION_LABEL         0
527
528IMAGEMODULE(
529   d64,
530   "Commodore SX64/VC1541/2031/1551 Diskette",   /* human readable name */
531   "d64",                        /* file extension */
532   NULL,                        /* crcfile */
533   NULL,                        /* crc system name */
534   EOLN_CR,                     /* eoln */
535   0,                           /* flags */
536   d64_image_init,            /* init function */
537   d64_image_exit,            /* exit function */
538   d64_image_info,      /* info function */
539   d64_image_beginenum,         /* begin enumeration */
540   d64_image_nextenum,         /* enumerate next */
541   d64_image_closeenum,         /* close enumeration */
542   d64_image_freespace,          /*  free space on image    */
543   d64_image_readfile,         /* read file */
544   d64_image_writefile,         /* write file */
545   d64_image_deletefile,         /* delete file */
546   d64_image_create,            /* create image */
547   d64_read_sector,
548   d64_write_sector,
549   NULL,                        /* file options */
550   d64_createopts                  /* create options */
551)
552
553IMAGEMODULE(
554   x64,
555   "Commodore VC1541 Diskette",   /* human readable name */
556   "x64",                        /* file extension */
557   NULL,                        /* crcfile */
558   NULL,                        /* crc system name */
559   EOLN_CR,                     /* eoln */
560   0,                           /* flags */
561   x64_image_init,            /* init function */
562   d64_image_exit,            /* exit function */
563   d64_image_info,      /* info function */
564   d64_image_beginenum,         /* begin enumeration */
565   d64_image_nextenum,         /* enumerate next */
566   d64_image_closeenum,         /* close enumeration */
567   d64_image_freespace,          /* free space on image    */
568   d64_image_readfile,         /* read file */
569   d64_image_writefile,         /* write file */
570   d64_image_deletefile,         /* delete file */
571   x64_image_create,            /* create image */
572   d64_read_sector,
573   d64_write_sector,
574   NULL,                        /* file options */
575   d64_createopts                  /* create options */
576)
577
578IMAGEMODULE(
579   d71,
580   "Commodore 128D/1571 Diskette",   /* human readable name */
581   "d71",                        /* file extension */
582   NULL,                        /* crcfile */
583   NULL,                        /* crc system name */
584   EOLN_CR,                     /* eoln */
585   0,                           /* flags */
586   d71_image_init,            /* init function */
587   d64_image_exit,            /* exit function */
588   d64_image_info,      /* info function */
589   d64_image_beginenum,         /* begin enumeration */
590   d64_image_nextenum,         /* enumerate next */
591   d64_image_closeenum,         /* close enumeration */
592   d71_image_freespace,          /*  free space on image    */
593   d64_image_readfile,         /* read file */
594   d64_image_writefile,         /* write file */
595   d64_image_deletefile,         /* delete file */
596   d71_image_create,            /* create image */
597   d64_read_sector,
598   d64_write_sector,
599   NULL,                        /* file options */
600   d64_createopts                  /* create options */
601)
602
603IMAGEMODULE(
604   d81,
605   "Commodore 65/1565/1581 Diskette",   /* human readable name */
606   "d81",                        /* file extension */
607   NULL,                        /* crcfile */
608   NULL,                        /* crc system name */
609   EOLN_CR,                     /* eoln */
610   0,                           /* flags */
611   d81_image_init,            /* init function */
612   d64_image_exit,            /* exit function */
613   d81_image_info,      /* info function */
614   d64_image_beginenum,         /* begin enumeration */
615   d64_image_nextenum,         /* enumerate next */
616   d64_image_closeenum,         /* close enumeration */
617   d81_image_freespace,          /*  free space on image    */
618   d64_image_readfile,         /* read file */
619   d64_image_writefile,         /* write file */
620   d64_image_deletefile,         /* delete file */
621   d81_image_create,            /* create image */
622   d64_read_sector,
623   d64_write_sector,
624   NULL,                        /* file options */
625   d64_createopts                  /* create options */
626)
627
628static int d64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
629{
630   d64_image *image;
631
632   d64_open_helper();
633   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
634   if (!image) return IMGTOOLERR_OUTOFMEMORY;
635
636   memset(image, 0, sizeof(d64_image));
637   image->base.module = mod;
638   image->size=stream_size(f);
639   image->file_handle=f;
640   image->get_offset=d64_tracksector2offset;
641   image->alloc_sector=d64_alloc_sector;
642   image->free_sector=d64_free_sector;
643   image->directory.track=18;image->directory.sector=0;
644   image->bam_bytes_dir_track=3;
645   image->d64=1;
646
647   switch (image->size) {
648   case 174848: image->tracks=35;break;
649   case 175531: image->tracks=35;image->crc=1;break;
650   case 196608: image->tracks=40;break;
651   case 197376: image->tracks=40;image->crc=1;break;
652   default:
653      free(image);
654      *outimg=NULL;
655      return IMGTOOLERR_CORRUPTIMAGE;
656   }
657
658   image->realimage = (unsigned char *) malloc(image->size);
659   image->data = image->realimage;
660   if ( (!image->data)
661       ||(stream_read(f, image->data, image->size)!=image->size) ) {
662      free(image);
663      *outimg=NULL;
664      return IMGTOOLERR_OUTOFMEMORY;
665   }
666
667   return 0;
668}
669
670static int x64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
671{
672   d64_image *image;
673
674   d64_open_helper();
675   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
676   if (!image) return IMGTOOLERR_OUTOFMEMORY;
677
678   memset(image, 0, sizeof(d64_image));
679   image->base.module = mod;
680   image->size=stream_size(f);
681   image->file_handle=f;
682   image->get_offset=d64_tracksector2offset;
683   image->alloc_sector=d64_alloc_sector;
684   image->free_sector=d64_free_sector;
685   image->directory.track=18;image->directory.sector=0;
686   image->bam_bytes_dir_track=3;
687   image->x64=1;
688   switch (image->size) {
689   case 174848+0x40: image->tracks=35;break;
690   case 175531+0x40: image->tracks=35;image->crc=1;break;
691   case 196608+0x40: image->tracks=40;break;
692   case 197376+0x40: image->tracks=40;image->crc=1;break;
693   default:
694      free(image);
695      *outimg=NULL;
696      return IMGTOOLERR_CORRUPTIMAGE;
697   }
698
699   image->realimage = (unsigned char *) malloc(image->size);
700   image->data = image->realimage+0x40;
701   if ( (!image->realimage)
702       ||(stream_read(f, image->realimage, image->size)!=image->size) ) {
703      free(image);
704      *outimg=NULL;
705      return IMGTOOLERR_OUTOFMEMORY;
706   }
707
708   return 0;
709}
710
711static int d71_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
712{
713   d64_image *image;
714
715   d64_open_helper();
716   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
717   if (!image) return IMGTOOLERR_OUTOFMEMORY;
718
719   memset(image, 0, sizeof(d64_image));
720   image->base.module = mod;
721   image->size=stream_size(f);
722   image->file_handle=f;
723   image->get_offset=d71_tracksector2offset;
724   image->alloc_sector=d71_alloc_sector;
725   image->free_sector=d71_free_sector;
726   image->directory.track=18;image->directory.sector=0;
727   image->d71=1;
728   image->tracks=70;
729
730   image->realimage = (unsigned char *) malloc(image->size);
731   image->data = image->realimage;
732   if ( (!image->data)
733       ||(stream_read(f, image->data, image->size)!=image->size) ) {
734      free(image);
735      *outimg=NULL;
736      return IMGTOOLERR_OUTOFMEMORY;
737   }
738
739   return 0;
740}
741
742static int d81_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
743{
744   d64_image *image;
745
746   d64_open_helper();
747   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
748   if (!image) return IMGTOOLERR_OUTOFMEMORY;
749
750   memset(image, 0, sizeof(d64_image));
751   image->base.module = mod;
752   image->size=stream_size(f);
753   image->get_offset=d81_tracksector2offset;
754   image->alloc_sector=d81_alloc_sector;
755   image->free_sector=d81_free_sector;
756   image->directory.track=40;image->directory.sector=0;
757   image->d81=1;
758   image->tracks=80;
759   image->bam_bytes_dir_track=6;
760   image->file_handle=f;
761
762   image->realimage = (unsigned char *) malloc(image->size);
763   image->data = image->realimage;
764   if ( (!image->data)
765       ||(stream_read(f, image->data, image->size)!=image->size) ) {
766      free(image);
767      *outimg=NULL;
768      return IMGTOOLERR_OUTOFMEMORY;
769   }
770
771   return 0;
772}
773
774static void d64_image_exit(imgtool_image *img)
775{
776   d64_image *image=(d64_image*)img;
777   if (image->modified) {
778      stream_seek(image->file_handle, 0, SEEK_SET);
779      stream_write(image->file_handle, image->realimage, image->size);
780   }
781   stream_close(image->file_handle);
782   free(image->realimage);
783   free(image);
784}
785
786static void d64_image_info(imgtool_image *img, char *string, const int len)
787{
788   d64_image *image=(d64_image*)img;
789   char name[17]={ 0 };
790
791   int pos=image->get_offset(image->directory.track,image->directory.sector);
792
793   cbm_filename_to_cstring((unsigned char *)image->data+pos+0x90, 16,
794      (unsigned char*)name);
795   if ((image->d64)||(image->x64)) {
796      sprintf(string, "%d tracks%s\n%-16s %c%c %c%c",
797            image->tracks, image->crc?" with crc":"",
798            name,
799            image->data[pos + 162], image->data[pos + 163],
800            image->data[pos + 165], image->data[pos + 166] );
801   } else {
802      sprintf(string, "%-16s %c%c %c%c",
803            name,
804            image->data[pos + 162], image->data[pos + 163],
805            image->data[pos + 165], image->data[pos + 166] );
806   }
807}
808
809static void d81_image_info(imgtool_image *img, char *string, const int len)
810{
811   d64_image *image=(d64_image*)img;
812   char name[17]={ 0 };
813
814   int pos=image->get_offset(image->directory.track,image->directory.sector);
815
816   cbm_filename_to_cstring((unsigned char *)image->data+pos+4, 16,
817      (unsigned char *)name);
818   sprintf(string, "%d tracks%s\n%-16s %c%c %c%c",
819         image->tracks, image->crc?" with crc":"",
820         name,
821         image->data[pos + 22], image->data[pos + 23],
822         image->data[pos + 25], image->data[pos + 26] );
823}
824
825static int d64_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
826{
827   d64_image *image=(d64_image*)img;
828   d64_iterator *iter;
829   int pos;
830
831   iter=*(d64_iterator**)outenum = (d64_iterator *) malloc(sizeof(d64_iterator));
832   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
833
834   iter->base.module = img->module;
835
836   iter->image=image;
837   pos = image->get_offset (image->directory.track, image->directory.sector);
838   iter->track = iter->image->data[pos];
839   iter->sector = iter->image->data[pos + 1];
840   iter->offset = 2;
841   return 0;
842}
843
844static int d64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
845{
846   d64_iterator *iter=(d64_iterator*)enumeration;
847   int pos;
848
849   ent->corrupt=0;
850   ent->eof=0;
851   
852   while ((iter->track >= 1) && (iter->track <= iter->image->tracks)) //safer
853//   while (iter->track != 0)
854   {
855      pos = iter->image->get_offset(iter->track, iter->sector);
856      for (; iter->offset<256; iter->offset += 32)
857      {
858         if (iter->image->data[pos + iter->offset] & 0x80)
859         {
860            cbm_filename_to_cstring(
861               (unsigned char*)iter->image->data+pos+iter->offset+3,
862               16, (unsigned char *)ent->fname);
863
864            ent->filesize=iter->image->data[pos+iter->offset+28]
865               +(iter->image->data[pos+iter->offset+29]<<8); // in blocks
866
867            if (ent->attr) {
868               switch (iter->image->data[pos+iter->offset]&FILE_TYPE_MASK) {
869               case FILE_TYPE_DEL: sprintf(ent->attr,"DEL");break;
870               case FILE_TYPE_SEQ: sprintf(ent->attr,"SEQ");break;
871               case FILE_TYPE_PRG: sprintf(ent->attr,"PRG");break;
872               case FILE_TYPE_USR: sprintf(ent->attr,"USR");break;
873               case FILE_TYPE_REL: sprintf(ent->attr,"REL");break;
874               default: sprintf(ent->attr,"unknown!");break;
875               }
876            }
877            iter->offset+=32;
878            return 0;
879         }
880      }
881      iter->track = iter->image->data[pos];
882      iter->sector = iter->image->data[pos + 1];
883      iter->offset = 2;
884   }
885
886   ent->eof=1;
887   return 0;
888}
889
890static void d64_image_closeenum(imgtool_directory *enumeration)
891{
892   free(enumeration);
893}
894
895static size_t d64_image_freespace(imgtool_image *img)
896{
897   d64_image *image=(d64_image*)img;
898   int i, j, pos;
899   size_t blocksfree = 0;
900
901   pos = image->get_offset(image->directory.track, image->directory.sector);
902   blocksfree = 0;
903   for (j = 1, i = 4; j <= 35; j++, i += 4) // no more room for BAM!
904   {
905      blocksfree += image->data[pos + i];
906   }
907
908   return blocksfree;
909}
910
911static size_t d71_image_freespace(imgtool_image *img)
912{
913   d64_image *image=(d64_image*)img;
914   int i, j, pos;
915   size_t blocksfree = 0;
916
917   pos = image->get_offset(image->directory.track, image->directory.sector);
918   blocksfree = 0;
919   for (j = 1, i = 4; j <= 35; j++, i += 4)
920   {
921      blocksfree += image->data[pos + i];
922   }
923   for (i = 221; j <= 70; j++, i ++)
924   {
925      blocksfree += image->data[pos + i];
926   }
927
928   return blocksfree;
929}
930
931static size_t d81_image_freespace(imgtool_image *img)
932{
933   d64_image *image=(d64_image*)img;
934   int j,k;
935   size_t blocksfree = 0;
936
937   for (k=1; k<=2; k++) {
938      D81_BAM *bam=(D81_BAM*)(image->data+image->get_offset(40,k));
939      for (j = 1; j <= 40; j++)
940      {
941         blocksfree += bam->bam[j-1].free;
942      }
943   }
944
945   return blocksfree;
946}
947
948static int d64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
949{
950   d64_image *image=(d64_image*)img;
951   int pos;
952   D64_ENTRY *entry;
953
954   if ((entry=d64_image_findfile(image, (const unsigned char *)fname))==NULL )
955      return IMGTOOLERR_MODULENOTFOUND;
956
957   pos = image->get_offset(entry->track, entry->sector);
958
959   while (image->data[pos]!=0) {
960      if (stream_write(destf, image->data+pos+2, 254)!=254)
961         return IMGTOOLERR_WRITEERROR;
962     
963      pos = image->get_offset (image->data[pos + 0], image->data[pos + 1]);
964   }
965   if (image->data[pos+1]-1>0) {
966      if (stream_write(destf, image->data+pos+2, image->data[pos+1]-1)!=image->data[pos+1]-1)
967         return IMGTOOLERR_WRITEERROR;
968   }
969
970   return 0;
971}
972
973static int d64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_)
974{
975   d64_image *image=(d64_image*)img;
976   int fsize, pos, i, b, freespace;
977   int track, sector;
978   D64_ENTRY *entry;
979
980   fsize=stream_size(sourcef)+1;
981
982   imgtool_partition_get_free_space(img, &freespace);
983
984   if ((entry=d64_image_findfile(image, (const unsigned char *)fname))!=NULL ) {
985      /* overriding */
986      if ((freespace + GET_UWORD(entry->blocks))*254<fsize)
987         return IMGTOOLERR_NOSPACE;
988      track=entry->track;
989      sector=entry->sector;
990     
991      while (track!=0) {
992         image->free_sector(image, track, sector);
993         pos = image->get_offset(track, sector);
994         track=image->data[pos];
995         sector=image->data[pos+1];
996      }
997   } else {
998      if (freespace*254<fsize) return IMGTOOLERR_NOSPACE;
999      // search free entry
1000      entry=d64_get_free_entry(image);
1001   }
1002
1003   entry->type=FILE_TYPE_PRG|0x80;
1004   memset(entry->name, 0xa0, sizeof(entry->name));
1005   memcpy(entry->name, fname, strlen(fname));
1006
1007   image->alloc_sector(image, &track, &sector);
1008   entry->track=track;
1009   entry->sector=sector;
1010   pos = image->get_offset(track, sector);
1011
1012   for (i = 0, b=0; i + 254 < fsize; i += 254, b++)
1013   {
1014      if (stream_read(sourcef, image->data+pos+2, 254)!=254)
1015         return IMGTOOLERR_READERROR;
1016     
1017      image->alloc_sector(image, &track, &sector);
1018      image->data[pos]=track;
1019      image->data[pos+1]=sector;
1020      pos = image->get_offset (track, sector);
1021   }
1022   b++;
1023   image->data[pos]=0;
1024   image->data[pos+1]=fsize-i;
1025   if (fsize-i-1>0) {
1026      if (stream_read(sourcef, image->data+pos+2, fsize-i-1)!=fsize-i-1)
1027         return IMGTOOLERR_READERROR;
1028   }
1029   image->data[pos+2+fsize-i]=0;
1030   
1031   SET_UWORD(entry->blocks, b);
1032   image->modified=1;
1033
1034   return 0;
1035}
1036
1037static int d64_image_deletefile(imgtool_image *img, const char *fname)
1038{
1039   d64_image *image=(d64_image*)img;
1040   int pos;
1041   int sector, track;
1042   D64_ENTRY *entry;
1043
1044   if ((entry=d64_image_findfile(image, (const unsigned char *)fname))==NULL )
1045      return IMGTOOLERR_MODULENOTFOUND;
1046
1047   track=entry->track;
1048   sector=entry->sector;
1049
1050   while (track!=0) {
1051      image->free_sector(image, track, sector);
1052      pos = image->get_offset(track, sector);
1053      track=image->data[pos];
1054      sector=image->data[pos+1];
1055   }
1056
1057   image->modified=1;
1058   return 0;
1059}
1060
1061static int d64_read_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, void *buffer, int length)
1062{
1063   /* not yet implemented */
1064   assert(0);
1065   return IMGTOOLERR_UNEXPECTED;
1066}
1067
1068static int d64_write_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, const void *buffer, int length)
1069{
1070   /* not yet implemented */
1071   assert(0);
1072   return IMGTOOLERR_UNEXPECTED;
1073}
1074
1075static int d64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1076{
1077   unsigned char sector[0x100]={0};
1078   int tracks=35;
1079   int crc=0;
1080   int t,s,i;
1081
1082   for (t=1; t<=tracks; t++) {
1083      for (s=0; s<d64_sectors_per_track[t-1]; s++) {
1084         if ((t==18)&&(s==0)) {
1085            for (i=1; i<=35; i++) {
1086               d64_header.bam[i-1].free=d64_sectors_per_track[i-1];
1087               d64_header.bam[i-1].map[0]=0xff;
1088               d64_header.bam[i-1].map[1]=0xff;
1089               switch (d64_header.bam[i-1].free) {
1090               case 17: d64_header.bam[i-1].map[2]=1;break;
1091               case 18: d64_header.bam[i-1].map[2]=3;break;
1092               case 19: d64_header.bam[i-1].map[2]=7;break;
1093               case 21: d64_header.bam[i-1].map[2]=0x1f;break;
1094               }
1095               if (i==18) { // allocate the 2 directory sectors
1096                  d64_header.bam[i-1].free-=2;
1097                  d64_header.bam[i-1].map[0]&=~3;
1098               }
1099            }
1100            //d64_header.name=0xa0;
1101            //d64_header.id=0xa0;
1102            if (stream_write(f, &d64_header, sizeof(d64_header)) != sizeof(d64_header))
1103               return  IMGTOOLERR_WRITEERROR;
1104         } else {
1105            if (stream_write(f, &sector, sizeof(sector)) != sizeof(sector))
1106               return  IMGTOOLERR_WRITEERROR;
1107         }
1108      }
1109   }
1110   if (crc) {
1111      for (t=1; t<=tracks; t++) {
1112         if (stream_write(f, &d64_header, d64_sectors_per_track[t-1])
1113            != d64_sectors_per_track[t-1])
1114            return  IMGTOOLERR_WRITEERROR;
1115         }
1116   }
1117   return 0;
1118}
1119
1120static int x64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1121{
1122   struct {
1123      unsigned char data[0x40];
1124   } x64_header={
1125      { 0x43, 0x15, 0x41, 0x64,
1126        0x01, 0x02, 0x01, 0x23,
1127        0x01
1128      }
1129   };
1130   if (stream_write(f, &x64_header, sizeof(x64_header)) != sizeof(x64_header))
1131      return  IMGTOOLERR_WRITEERROR;
1132
1133   d64_image_create(mod, f, options_);
1134   return 0;
1135}
1136
1137static int d71_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1138{
1139   D71_HEADER d71_header= { { 0 } };
1140   unsigned char sector[0x100]={0};
1141   int t,s,i;
1142
1143   for (t=1; t<=70; t++) {
1144      for (s=0; s<d71_sectors_per_track[t-1]; s++) {
1145         if ((t==18)&&(s==0)) {
1146            d64_header.doublesided=0x80;
1147            for (i=1; i<=35; i++) {
1148               d64_header.bam[i-1].free=d71_sectors_per_track[i-1];
1149               d64_header.bam[i-1].map[0]=0xff;
1150               d64_header.bam[i-1].map[1]=0xff;
1151               switch (d64_header.bam[i-1].free) {
1152               case 17: d64_header.bam[i-1].map[2]=1;break;
1153               case 18: d64_header.bam[i-1].map[2]=3;break;
1154               case 19: d64_header.bam[i-1].map[2]=7;break;
1155               case 21: d64_header.bam[i-1].map[2]=0x1f;break;
1156               }
1157               if (i==18) { // allocate the 2 directory sectors
1158                  d64_header.bam[i-1].free-=2;
1159                  d64_header.bam[i-1].map[0]&=~3;
1160               }
1161            }
1162            for (;i<=70;i++) {
1163               if (i!=18+35)
1164                  d64_header.free2[i-36]=d71_sectors_per_track[i-1];
1165               else
1166                  d64_header.free2[i-36]=0;
1167            }
1168            //d64_header.name=0xa0;
1169            //d64_header.id=0xa0;
1170            if (stream_write(f, &d64_header, sizeof(d64_header)) != sizeof(d64_header))
1171               return  IMGTOOLERR_WRITEERROR;
1172         } else if ((t==35+18)&&(s==0)) {
1173            for (i=36;i<=70;i++) {
1174               if (i!=18+35) {
1175                  d71_header.bam2[i-36].map2[0]=0xff;
1176                  d71_header.bam2[i-36].map2[1]=0xff;
1177                  switch (d64_header.free2[i-36]) {
1178                  case 17: d71_header.bam2[i-36].map2[2]=1;break;
1179                  case 18: d71_header.bam2[i-36].map2[2]=3;break;
1180                  case 19: d71_header.bam2[i-36].map2[2]=7;break;
1181                  case 21: d71_header.bam2[i-36].map2[2]=0x1f;break;
1182                  }
1183               } else {
1184                  d71_header.bam2[i-36].map2[0]=0;
1185                  d71_header.bam2[i-36].map2[1]=0;
1186                  d71_header.bam2[i-36].map2[2]=0;
1187               }
1188            }
1189            if (stream_write(f, &d71_header, sizeof(d71_header))
1190               != sizeof(d71_header))
1191               return  IMGTOOLERR_WRITEERROR;
1192         } else {
1193            if (stream_write(f, &sector, sizeof(sector)) != sizeof(sector))
1194               return  IMGTOOLERR_WRITEERROR;
1195         }
1196      }
1197   }
1198   return 0;
1199}
1200
1201static int d81_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1202{
1203   unsigned char sector[0x100]={0};
1204   unsigned char id[2]={'1','2'};
1205   int t,s,i;
1206
1207   for (t=1; t<=80; t++) {
1208      for (s=0; s<40; s++) {
1209         if ((t==40)&&(s==0)) {
1210            //d81_header.name=0xa0;
1211            d81_header.id[0]=id[0];
1212            d81_header.id[0]=id[1];
1213            if (stream_write(f, &d81_header, sizeof(d81_header)) != sizeof(d81_header))
1214               return  IMGTOOLERR_WRITEERROR;
1215         } else if ((t==40)&&(s==1)){
1216            d81_bam.id[0]=id[0];
1217            d81_bam.id[0]=id[1];
1218            for (i=1; i<=40; i++) {
1219               d81_bam.bam[i-1].free=40;
1220               d81_bam.bam[i-1].map[0]=0xff;
1221               d81_bam.bam[i-1].map[1]=0xff;
1222               d81_bam.bam[i-1].map[2]=0xff;
1223               d81_bam.bam[i-1].map[3]=0xff;
1224               d81_bam.bam[i-1].map[4]=0xff;
1225            }
1226            d81_bam.bam[40-1].free=36;
1227            d81_bam.bam[40-1].map[0]=0xf0;
1228            if (stream_write(f, &d81_bam, sizeof(d81_bam)) != sizeof(d81_bam))
1229               return  IMGTOOLERR_WRITEERROR;
1230            d81_bam.bam[40-1].free=40;
1231            d81_bam.bam[40-1].map[0]=0xff;
1232         } else if ((t==40)&&(s==2)){
1233            d81_bam.track=0;
1234            if (stream_write(f, &d81_bam, sizeof(d81_bam)) != sizeof(d81_bam))
1235               return  IMGTOOLERR_WRITEERROR;
1236         } else {
1237            if (stream_write(f, &sector, sizeof(sector)) != sizeof(sector))
1238               return  IMGTOOLERR_WRITEERROR;
1239         }
1240      }
1241   }
1242   return 0;
1243}
src/mess/tools/imgtool/macutil.c
r1339r1340
1/****************************************************************************
2
3   macutil.c
4
5   Imgtool Utility code for manipulating certain Apple/Mac data structures
6   and conventions
7
8*****************************************************************************/
9
10#include "macutil.h"
11
12
13time_t mac_crack_time(UINT32 t)
14{
15   /* not sure if this is correct... */
16   return t - (((1970 - 1904) * 365) + 17) * 24 * 60 * 60;
17}
18
19
20
21UINT32 mac_setup_time(time_t t)
22{
23   /* not sure if this is correct... */
24   return t + (((1970 - 1904) * 365) + 17) * 24 * 60 * 60;
25}
26
27
28
29UINT32 mac_time_now(void)
30{
31   time_t now;
32   time(&now);
33   return mac_setup_time(now);
34}
35
36
37
38imgtoolerr_t mac_identify_fork(const char *fork_string, mac_fork_t *fork_num)
39{
40   if (!strcmp(fork_string, ""))
41      *fork_num = MAC_FORK_DATA;
42   else if (!strcmp(fork_string, "RESOURCE_FORK"))
43      *fork_num = MAC_FORK_RESOURCE;
44   else
45      return IMGTOOLERR_FORKNOTFOUND;
46   return IMGTOOLERR_SUCCESS;
47}
48
49
50
51void mac_suggest_transfer(mac_filecategory_t file_category, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
52{
53   suggestions[0].viability = (file_category == MAC_FILECATEGORY_FORKED) ? SUGGESTION_RECOMMENDED : SUGGESTION_POSSIBLE;
54   suggestions[0].filter = filter_macbinary_getinfo;
55   suggestions[0].fork = NULL;
56   suggestions[0].description = NULL;
57
58   suggestions[1].viability = (file_category == MAC_FILECATEGORY_TEXT) ? SUGGESTION_RECOMMENDED : SUGGESTION_POSSIBLE;
59   suggestions[1].filter = filter_eoln_getinfo;
60   suggestions[1].fork = NULL;
61   suggestions[1].description = NULL;
62
63   suggestions[2].viability = (file_category == MAC_FILECATEGORY_DATA) ? SUGGESTION_RECOMMENDED : SUGGESTION_POSSIBLE;
64   suggestions[2].filter = NULL;
65   suggestions[2].fork = "";
66   suggestions[2].description = "Raw (data fork)";
67
68   suggestions[3].viability = SUGGESTION_POSSIBLE;
69   suggestions[3].filter = NULL;
70   suggestions[3].fork = "RESOURCE_FORK";
71   suggestions[3].description = "Raw (resource fork)";
72}
73
74
75
76void pascal_from_c_string(unsigned char *pstring, size_t pstring_len, const char *cstring)
77{
78   size_t cstring_len, i;
79
80   cstring_len = strlen(cstring);
81   pstring[0] = MIN(cstring_len, pstring_len - 1);
82
83   for (i = 0; i < pstring[0]; i++)
84      pstring[1 + i] = cstring[i];
85   while(i < pstring_len - 1)
86      pstring[1 + i++] = '\0';
87}
88
src/mess/tools/imgtool/mac.c
r1339r1340
1/****************************************************************************
2
3   mac.c
4
5   Handlers for Classic MacOS images (MFS and HFS formats).
6
7   Raphael Nabet, 2003
8
9   TODO:
10   * add support for HFS write
11
12*****************************************************************************
13
14   terminology:
15   disk block: 512-byte logical block.  With sectors of 512 bytes, one logical
16      block is equivalent to one sector; when the sector size is not 512
17      bytes, sectors are split or grouped to make 512-byte disk blocks.
18   allocation block: The File Manager always allocates logical disk blocks to
19      a file in groups called allocation blocks; an allocation block is
20      simply a group of consecutive logical blocks.  The size of a volume's
21      allocation blocks depends on the capacity of the volume; there can be
22      at most 4094 (MFS) or 65535 (HFS) allocation blocks on a volume.
23   MFS (Macintosh File System): File system used by the early Macintosh.  This
24      File system does not support folders (you may create folders on a MFS
25      disk, but such folders are not implemented on File System level but in
26      the Desktop file, and they are just a hint of how programs should list
27      files, i.e. you can't have two files with the same name on a volume
28      even if they are in two different folders), and it is not adequate for
29      large volumes.
30   HFS (Hierarchical File System): File system introduced with the HD20
31      harddisk, the Macintosh Plus ROMs, and system 3.2 (IIRC).  Contrary to
32      MFS, it supports hierarchical folders.  Also, it is suitable for larger
33      volumes.
34   HFS+ (HFS Plus): New file system introduced with MacOS 8.1.  It has a lot
35      in common with HFS, but it supports more allocation blocks (up to 4
36      billions IIRC), and many extra features, including longer file names
37      (up to 255 UTF-16 Unicode chars).
38   tag data: with the GCR encoding, each disk block is associated with a 12
39      (3.5" floppies) or 20 (HD20) byte tag record.  This tag record contains
40      information on the block allocation status (whether it is allocated
41      in a file or free, which file is it belongs to, what offset the block
42      has in the file).  This enables to recover all files whose data blocks
43      are still on the disk surface even if the disk catalog has been trashed
44      completely (though most file properties, like the name, type and
45      logical EOF, are not saved in the tag record and cannot be recovered).
46
47   Organization of an MFS volume:
48
49   Logical      Contents                           Allocation block
50   block
51
52   0 - 1:      System startup information
53   2 - m:      Master directory block (MDB)
54            + allocation block link pointers
55   m+1 - n:   Directory file
56   n+1 - p-2:   Other files and free space               0 - ((p-2)-(n+1))/k
57   p-1:      Alternate MDB
58   p:         Not used
59   usually, k = 2, m = 3, n = 16, p = 799 (SSDD 3.5" floppy)
60   with DSDD 3.5" floppy, I assume that p = 1599, but I don't know the other
61   values
62
63
64   Master Directory Block:
65
66   Offset  Length  Description
67   ------  ------  -----------
68        0       2  Volume Signature
69       2       4  Creation Date
70       6       4  Last Modification Date
71       10       2  Volume Attributes
72      12       2  Number of Files In Root Directory
73      14       2  First Block of Volume Bitmap
74      ...
75
76   Links:
77      http://developer.apple.com/documentation/mac/Files/Files-99.html
78      http://developer.apple.com/documentation/mac/Files/Files-100.html
79      http://developer.apple.com/documentation/mac/Files/Files-101.html
80      http://developer.apple.com/documentation/mac/Files/Files-102.html
81      http://developer.apple.com/documentation/mac/Files/Files-103.html
82      http://developer.apple.com/documentation/mac/Files/Files-104.html
83      http://developer.apple.com/documentation/mac/Files/Files-105.html
84      http://developer.apple.com/documentation/mac/Files/Files-106.html
85      http://developer.apple.com/documentation/mac/Devices/Devices-121.html#MARKER-2-169
86      http://developer.apple.com/documentation/mac/MoreToolbox/MoreToolbox-99.html
87
88*****************************************************************************/
89
90#include <ctype.h>
91#include <string.h>
92#include <time.h>
93#include <limits.h>
94#include <stddef.h>
95
96#include "osdepend.h"
97#include "imgtoolx.h"
98#include "macutil.h"
99#include "iflopimg.h"
100#include "formats/ap_dsk35.h"
101
102/* if 1, check consistency of B-Tree (most of the checks will eventually be
103   suppressed when the image is opened as read-only and only enabled when
104   the image is opened as read/write) */
105#define BTREE_CHECKS 1
106/* if 1, check consistency of tag data when we are at risk of corrupting the
107   disk (file write and allocation) */
108#define TAG_CHECKS 1
109/* if 1, check consistency of tag data when reading files (not recommended
110   IMHO) */
111#define TAG_EXTRA_CHECKS 0
112
113#if 0
114#pragma mark MISCELLANEOUS UTILITIES
115#endif
116
117typedef struct UINT16BE
118{
119   UINT8 bytes[2];
120} UINT16BE;
121
122typedef struct UINT24BE
123{
124   UINT8 bytes[3];
125} UINT24BE;
126
127typedef struct UINT32BE
128{
129   UINT8 bytes[4];
130} UINT32BE;
131
132INLINE UINT16 get_UINT16BE(UINT16BE word)
133{
134   return (word.bytes[0] << 8) | word.bytes[1];
135}
136
137INLINE void set_UINT16BE(UINT16BE *word, UINT16 data)
138{
139   word->bytes[0] = (data >> 8) & 0xff;
140   word->bytes[1] = data & 0xff;
141}
142
143INLINE UINT32 get_UINT24BE(UINT24BE word)
144{
145   return (word.bytes[0] << 16) | (word.bytes[1] << 8) | word.bytes[2];
146}
147
148INLINE void set_UINT24BE(UINT24BE *word, UINT32 data)
149{
150   word->bytes[0] = (data >> 16) & 0xff;
151   word->bytes[1] = (data >> 8) & 0xff;
152   word->bytes[2] = data & 0xff;
153}
154
155INLINE UINT32 get_UINT32BE(UINT32BE word)
156{
157   return (word.bytes[0] << 24) | (word.bytes[1] << 16) | (word.bytes[2] << 8) | word.bytes[3];
158}
159
160INLINE void set_UINT32BE(UINT32BE *word, UINT32 data)
161{
162   word->bytes[0] = (data >> 24) & 0xff;
163   word->bytes[1] = (data >> 16) & 0xff;
164   word->bytes[2] = (data >> 8) & 0xff;
165   word->bytes[3] = data & 0xff;
166}
167
168/*
169   Macintosh string: first byte is length
170*/
171typedef UINT8 mac_str27[28];
172typedef UINT8 mac_str31[32];
173typedef UINT8 mac_str63[64];
174typedef UINT8 mac_str255[256];
175
176/*
177   Macintosh type/creator code: 4 char value
178*/
179typedef UINT32BE mac_type;
180
181/*
182   point record, with the y and x coordinates
183*/
184typedef struct mac_point
185{
186   UINT16BE v;      /* actually signed */
187   UINT16BE h;      /* actually signed */
188} mac_point;
189
190/*
191   rect record, with the corner coordinates
192*/
193typedef struct mac_rect
194{
195   UINT16BE top;   /* actually signed */
196   UINT16BE left;   /* actually signed */
197   UINT16BE bottom;/* actually signed */
198   UINT16BE right;   /* actually signed */
199} mac_rect;
200
201/*
202   FInfo (Finder file info) record
203*/
204typedef struct mac_FInfo
205{
206   mac_type  type;         /* file type */
207   mac_type  creator;      /* file creator */
208   UINT16BE  flags;      /* Finder flags */
209   mac_point location;      /* file's location in window */
210                        /* If set to {0, 0}, and the inited flag is
211                        clear, the Finder will place the item
212                        automatically */
213   UINT16BE  fldr;         /* MFS: window that contains file */
214                        /* -3: trash */
215                        /* -2: desktop */
216                        /* -1: new folder template?????? */
217                        /* 0: disk window ("root") */
218                        /* > 0: specific folder, index of FOBJ resource??? */
219                        /* The FOBJ resource contains some folder info;
220                        the name of the resource is the folder name. */
221                     /* HFS & HFS+:
222                        System 7: The window in which the file’s icon appears
223                        System 8: reserved (set to 0) */
224} mac_FInfo;
225
226/*
227   FXInfo (Finder extended file info) record -- not found in MFS
228*/
229typedef struct mac_FXInfo
230{
231   UINT16BE iconID;      /* System 7: An ID number for the file’s icon; the
232                        numbers that identify icons are assigned by the
233                        Finder */
234                     /* System 8: Reserved (set to 0) */
235   UINT16BE reserved[3];   /* Reserved (set to 0) */
236   UINT8    script;      /* System 7: if high-bit is set, the script code
237                        for displaying the file name; ignored otherwise */
238                     /* System 8: Extended flags MSB(?) */
239   UINT8    XFlags;      /* Extended flags */
240   UINT16BE comment;      /* System 7: Comment ID if high-bit is clear */
241                     /* System 8: Reserved (set to 0) */
242   UINT32BE putAway;      /* Put away folder ID (i.e. if the user moves the
243                        file onto the desktop, the directory ID of the
244                        folder from which the user moves the file is
245                        saved here) */
246} mac_FXInfo;
247
248/*
249   DInfo (Finder folder info) record -- not found in MFS
250*/
251typedef struct mac_DInfo
252{
253   mac_rect rect;         /* Folder's window bounds */
254   UINT16BE flags;         /* Finder flags, e.g. kIsInvisible, kNameLocked, etc */
255   mac_point location;      /* Location of the folder in parent window */
256                        /* If set to {0, 0}, and the initied flag is
257                        clear, the Finder will place the item
258                        automatically */
259   UINT16BE view;         /* System 7: The manner in which folders are
260                        displayed */
261                     /* System 8: reserved (set to 0) */
262} mac_DInfo;
263
264/*
265   DXInfo (Finder extended folder info) record -- not found in MFS
266*/
267typedef struct mac_DXInfo
268{
269   mac_point scroll;      /* Scroll position */
270   UINT32BE openChain;      /* System 7: chain of directory IDs for open folders */
271                     /* System 8: reserved (set to 0) */
272   UINT8    script;      /* System 7: if high-bit is set, the script code
273                        for displaying the folder name; ignored otherwise */
274                     /* System 8: Extended flags MSB(?) */
275   UINT8    XFlags;      /* Extended flags */
276   UINT16BE comment;      /* System 7: Comment ID if high-bit is clear */
277                     /* System 8: Reserved (set to 0) */
278   UINT32BE putAway;      /* Put away folder ID (i.e. if the user moves the
279                        folder onto the desktop, the directory ID of
280                        the folder from which the user moves it is
281                        saved here) */
282} mac_DXInfo;
283
284/*
285   defines for FInfo & DInfo flags fields
286*/
287enum
288{
289   fif_isOnDesk         = 0x0001,   /* System 6: set if item is located on desktop (files and folders) */
290                              /* System 7: Unused (set to 0) */
291   fif_color            = 0x000E,   /* color coding (files and folders) */
292   fif_colorReserved      = 0x0010,   /* System 6: reserved??? */
293                              /* System 7: Unused (set to 0) */
294   fif_requiresSwitchLaunch= 0x0020,   /* System 6: ??? */
295                              /* System 7: Unused (set to 0) */
296   fif_isShared         = 0x0040,   /* Applications files: if set, the */
297                                 /* application can be executed by */
298                                 /* multiple users simultaneously. */
299                              /* Otherwise, set to 0. */
300   fif_hasNoINITs         = 0x0080,   /* Extensions/Control Panels: if set(?), */
301                                 /* this file contains no INIT */
302                                 /* resource */
303                              /* Otherwise, set to 0. */
304   fif_hasBeenInited      = 0x0100,   /* System 6: The Finder has recorded information from
305                                 the file’s bundle resource into the desktop
306                                 database and given the file or folder a
307                                 position on the desktop. */
308                              /* System 7? 8?: Clear if the file contains desktop database */
309                                 /* resources ('BNDL', 'FREF', 'open', 'kind'...) */
310                                 /* that have not been added yet. Set only by the Finder */
311                                 /* Reserved for folders - make sure this bit is cleared for folders */
312
313   /* bit 0x0200 was at a point (AOCE for system 7.x?) the letter bit for
314   AOCE, but was reserved before and it is reserved again in recent MacOS
315   releases. */
316
317   fif_hasCustomIcon      = 0x0400,   /* (files and folders) */
318   fif_isStationery      = 0x0800,   /* System 7: (files only) */
319   fif_nameLocked         = 0x1000,   /* (files and folders) */
320   fif_hasBundle         = 0x2000,   /* Files only */
321   fif_isInvisible         = 0x4000,   /* (files and folders) */
322   fif_isAlias            = 0x8000   /* System 7: (files only) */
323};
324
325/*
326   mac_to_c_strncpy()
327
328   Encode a macintosh string as a C string.  The NUL character is escaped,
329   using the "%00" sequence.  To avoid any ambiguity, '%' is escaped with
330   '%25'.
331
332   dst (O): C string
333   n (I): length of buffer pointed to by dst
334   src (I): macintosh string (first byte is length)
335*/
336static void mac_to_c_strncpy(char *dst, int n, UINT8 *src)
337{
338   size_t len = src[0];
339   int i, j;
340
341   i = j = 0;
342   while ((i < len) && (j < n-1))
343   {
344      switch (src[i+1])
345      {
346      case '\0':
347         if (j >= n-3)
348            goto exit;
349         dst[j] = '%';
350         dst[j+1] = '0';
351         dst[j+2] = '0';
352         j += 3;
353         break;
354
355      case '%':
356         if (j >= n-3)
357            goto exit;
358         dst[j] = '%';
359         dst[j+1] = '2';
360         dst[j+2] = '5';
361         j += 3;
362         break;
363
364      default:
365         dst[j] = src[i+1];
366         j++;
367         break;
368      }
369      i++;
370   }
371
372exit:
373   if (n > 0)
374      dst[j] = '\0';
375}
376
377/*
378   c_to_mac_strncpy()
379
380   Decode a C string to a macintosh string.  The NUL character is escaped,
381   using the "%00" sequence.  To avoid any ambiguity, '%' is escaped with
382   '%25'.
383
384   dst (O): macintosh string (first byte is length)
385   src (I): C string
386   n (I): length of string pointed to by src
387*/
388static void c_to_mac_strncpy(mac_str255 dst, const char *src, int n)
389{
390   size_t len;
391   int i;
392   char buf[3];
393
394
395   len = 0;
396   i = 0;
397   while ((i < n) && (len < 255))
398   {
399      switch (src[i])
400      {
401      case '%':
402         if (i >= n-2)
403            goto exit;
404         buf[0] = src[i+1];
405         buf[1] = src[i+2];
406         buf[2] = '\0';
407         dst[len+1] = strtoul(buf, NULL, 16);
408         i += 3;
409         break;
410
411      default:
412         dst[len+1] = src[i];
413         i++;
414         break;
415      }
416      len++;
417   }
418
419exit:
420   dst[0] = len;
421}
422
423/*
424   mac_strcmp()
425
426   Compare two macintosh strings
427
428   s1 (I): the string to compare
429   s2 (I): the comparison string
430
431   Return a zero if s1 and s2 are equal, a negative value if s1 is less than
432   s2, and a positive value if s1 is greater than s2.
433*/
434/*static int mac_strcmp(const UINT8 *s1, const UINT8 *s2)
435{
436   size_t common_len;
437
438   common_len = (s1[0] <= s2[0]) ? s1[0] : s2[0];
439
440   return memcmp(s1+1, s2+1, common_len) || ((int)s1[0] - s2[0]);
441}*/
442
443/*
444   mac_stricmp()
445
446   Compare two macintosh strings in a manner compatible with the macintosh HFS
447   file system.
448
449   This functions emulates the way HFS (and MFS???) sorts string: this is
450   equivalent to the RelString macintosh toolbox call with the caseSensitive
451   parameter as false and the diacSensitive parameter as true.
452
453   s1 (I): the string to compare
454   s2 (I): the comparison string
455
456   Return a zero if s1 and s2 are equal, a negative value if s1 is less than
457   s2, and a positive value if s1 is greater than s2.
458
459Known issues:
460   Using this function makes sense with the MacRoman encoding, as it means the
461   computer will regard "DeskTop File", "Desktop File", "Desktop file", etc,
462   as the same file.  (UNIX users will probably regard this as an heresy, but
463   you must consider that, unlike UNIX, the Macintosh was not designed for
464   droids, but error-prone human beings that may forget about case.)
465
466   (Also, letters with diatrical signs follow the corresponding letters
467   without diacritical signs in the HFS catalog file.  This does not matter,
468   though, since the Finder will not display files in the HFS catalog order,
469   but it will instead sort files according to whatever order is currently
470   selected in the View menu.)
471
472   However, with other text encodings, the behavior will be completely absurd.
473   For instance, with the Greek encoding, it will think that the degree symbol
474   is the same letter (with different case) as the upper-case Psi, so that if
475   a program asks for a file called "90°" on a greek HFS volume, and there is
476   a file called "90Ψ" on this volume, file "90Ψ" will be opened.
477   Results will probably be even weirder with 2-byte scripts like Japanese or
478   Chinese.  Of course, we are not going to fix this issue, since doing so
479   would break the compatibility with the original Macintosh OS.
480*/
481
482static int mac_stricmp(const UINT8 *s1, const UINT8 *s2)
483{
484   static const unsigned char mac_char_sort_table[256] =
485   {
486   /*   \x00   \x01   \x02   \x03   \x04   \x05   \x06   \x07 */
487      0x00,   0x01,   0x02,   0x03,   0x04,   0x05,   0x06,   0x07,
488   /*   \x08   \x09   \x0a   \x0b   \x0c   \x0d   \x0e   \x0f */
489      0x08,   0x09,   0x0a,   0x0b,   0x0c,   0x0d,   0x0e,   0x0f,
490   /*   \x10   \x11   \x12   \x13   \x14   \x15   \x16   \x17 */
491      0x10,   0x11,   0x12,   0x13,   0x14,   0x15,   0x16,   0x17,
492   /*   \x18   \x19   \x1a   \x1b   \x1c   \x1d   \x1e   \x1f */
493      0x18,   0x19,   0x1a,   0x1b,   0x1c,   0x1d,   0x1e,   0x1f,
494   /*   \x20   \x21   \x22   \x23   \x24   \x25   \x26   \x27 */
495      0x20,   0x21,   0x22,   0x27,   0x28,   0x29,   0x2a,   0x2b,
496   /*   \x28   \x29   \x2a   \x2b   \x2c   \x2d   \x2e   \x2f */
497      0x2e,   0x2f,   0x30,   0x31,   0x32,   0x33,   0x34,   0x35,
498   /*   \x30   \x31   \x32   \x33   \x34   \x35   \x36   \x37 */
499      0x36,   0x37,   0x38,   0x39,   0x3a,   0x3b,   0x3c,   0x3d,
500   /*   \x38   \x39   \x3a   \x3b   \x3c   \x3d   \x3e   \x3f */
501      0x3e,   0x3f,   0x40,   0x41,   0x42,   0x43,   0x44,   0x45,
502   /*   \x40   \x41   \x42   \x43   \x44   \x45   \x46   \x47 */
503      0x46,   0x47,   0x51,   0x52,   0x54,   0x55,   0x5a,   0x5b,
504   /*   \x48   \x49   \x4a   \x4b   \x4c   \x4d   \x4e   \x4f */
505      0x5c,   0x5d,   0x62,   0x63,   0x64,   0x65,   0x66,   0x68,
506   /*   \x50   \x51   \x52   \x53   \x54   \x55   \x56   \x57 */
507      0x71,   0x72,   0x73,   0x74,   0x76,   0x77,   0x7c,   0x7d,
508   /*   \x58   \x59   \x5a   \x5b   \x5c   \x5d   \x5e   \x5f */
509      0x7e,   0x7f,   0x81,   0x82,   0x83,   0x84,   0x85,   0x86,
510   /*   \x60   \x61   \x62   \x63   \x64   \x65   \x66   \x67 */
511      0x4d,   0x47,   0x51,   0x52,   0x54,   0x55,   0x5a,   0x5b,
512   /*   \x68   \x69   \x6a   \x6b   \x6c   \x6d   \x6e   \x6f */
513      0x5c,   0x5d,   0x62,   0x63,   0x64,   0x65,   0x66,   0x68,
514   /*   \x70   \x71   \x72   \x73   \x74   \x75   \x76   \x77 */
515      0x71,   0x72,   0x73,   0x74,   0x76,   0x77,   0x7c,   0x7d,
516   /*   \x78   \x79   \x7a   \x7b   \x7c   \x7d   \x7e   \x7f */
517      0x7e,   0x7f,   0x81,   0x87,   0x88,   0x89,   0x8a,   0x8b,
518   /*   \x80   \x81   \x82   \x83   \x84   \x85   \x86   \x87 */
519      0x49,   0x4b,   0x53,   0x56,   0x67,   0x69,   0x78,   0x4e,
520   /*   \x88   \x89   \x8a   \x8b   \x8c   \x8d   \x8e   \x8f */
521      0x48,   0x4f,   0x49,   0x4a,   0x4b,   0x53,   0x56,   0x57,
522   /*   \x90   \x91   \x92   \x93   \x94   \x95   \x96   \x97 */
523      0x58,   0x59,   0x5e,   0x5f,   0x60,   0x61,   0x67,   0x6d,
524   /*   \x98   \x99   \x9a   \x9b   \x9c   \x9d   \x9e   \x9f */
525      0x6e,   0x6f,   0x69,   0x6a,   0x79,   0x7a,   0x7b,   0x78,
526   /*   \xa0   \xa1   \xa2   \xa3   \xa4   \xa5   \xa6   \xa7 */
527      0x8c,   0x8d,   0x8e,   0x8f,   0x90,   0x91,   0x92,   0x75,
528   /*   \xa8   \xa9   \xaa   \xab   \xac   \xad   \xae   \xaf */
529      0x93,   0x94,   0x95,   0x96,   0x97,   0x98,   0x4c,   0x6b,
530   /*   \xb0   \xb1   \xb2   \xb3   \xb4   \xb5   \xb6   \xb7 */
531      0x99,   0x9a,   0x9b,   0x9c,   0x9d,   0x9e,   0x9f,   0xa0,
532   /*   \xb8   \xb9   \xba   \xbb   \xbc   \xbd   \xbe   \xbf */
533      0xa1,   0xa2,   0xa3,   0x50,   0x70,   0xa4,   0x4c,   0x6b,
534   /*   \xc0   \xc1   \xc2   \xc3   \xc4   \xc5   \xc6   \xc7 */
535      0xa5,   0xa6,   0xa7,   0xa8,   0xa9,   0xaa,   0xab,   0x25,
536   /*   \xc8   \xc9   \xca   \xcb   \xcc   \xcd   \xce   \xcf */
537      0x26,   0xac,   0x20,   0x48,   0x4a,   0x6a,   0x6c,   0x6c,
538   /*   \xd0   \xd1   \xd2   \xd3   \xd4   \xd5   \xd6   \xd7 */
539      0xad,   0xae,   0x23,   0x24,   0x2c,   0x2d,   0xaf,   0xb0,
540   /*   \xd8   \xd9   \xda   \xdb   \xdc   \xdd   \xde   \xdf */
541      0x80,   0xb1,   0xb2,   0xb3,   0xb4,   0xb5,   0xb6,   0xb7,
542   /*   \xe0   \xe1   \xe2   \xe3   \xe4   \xe5   \xe6   \xe7 */
543      0xb8,   0xb9,   0xba,   0xbb,   0xbc,   0xbd,   0xbe,   0xbf,
544   /*   \xe8   \xe9   \xea   \xeb   \xec   \xed   \xee   \xef */
545      0xc0,   0xc1,   0xc2,   0xc3,   0xc4,   0xc5,   0xc6,   0xc7,
546   /*   \xf0   \xf1   \xf2   \xf3   \xf4   \xf5   \xf6   \xf7 */
547      0xc8,   0xc9,   0xca,   0xcb,   0xcc,   0xcd,   0xce,   0xcf,
548   /*   \xf8   \xf9   \xfa   \xfb   \xfc   \xfd   \xfe   \xff */
549      0xd0,   0xd1,   0xd2,   0xd3,   0xd4,   0xd5,   0xd6,   0xd7
550   };
551
552   size_t common_len;
553   int i;
554   int c1, c2;
555
556   common_len = (s1[0] <= s2[0]) ? s1[0] : s2[0];
557
558   for (i=0; i<common_len; i++)
559   {
560      c1 = mac_char_sort_table[s1[i+1]];
561      c2 = mac_char_sort_table[s2[i+1]];
562      if (c1 != c2)
563         return c1 - c2;
564   }
565
566   return ((int)s1[0] - s2[0]);
567}
568
569/*
570   mac_strcpy()
571
572   Copy a macintosh string
573
574   dst (O): dest macintosh string
575   src (I): source macintosh string (first byte is length)
576
577   Return a zero if s1 and s2 are equal, a negative value if s1 is less than
578   s2, and a positive value if s1 is greater than s2.
579*/
580INLINE void mac_strcpy(UINT8 *dest, const UINT8 *src)
581{
582   memcpy(dest, src, src[0]+1);
583}
584
585#ifdef UNUSED_FUNCTION
586/*
587   mac_strncpy()
588
589   Copy a macintosh string
590
591   dst (O): dest macintosh string
592   n (I): max string length for dest (range 0-255, buffer length + 1)
593   src (I): source macintosh string (first byte is length)
594*/
595static void mac_strncpy(UINT8 *dest, int n, const UINT8 *src)
596{
597   size_t len;
598
599   len = src[0];
600   if (len > n)
601      len = n;
602   dest[0] = len;
603   memcpy(dest+1, src+1, len);
604}
605#endif
606
607/*
608   disk image reference
609*/
610typedef struct mac_l1_imgref
611{
612   imgtool_image *image;
613   UINT32 heads;
614} mac_l1_imgref;
615
616
617
618static imgtoolerr_t mac_find_block(mac_l1_imgref *image, int block,
619   UINT32 *track, UINT32 *head, UINT32 *sector)
620{
621   *track = 0;
622   while(block >= (apple35_sectors_per_track(imgtool_floppy(image->image), *track) * image->heads))
623   {
624      block -= (apple35_sectors_per_track(imgtool_floppy(image->image), (*track)++) * image->heads);
625      if (*track >= 80)
626         return IMGTOOLERR_SEEKERROR;
627   }
628
629   *head = block / apple35_sectors_per_track(imgtool_floppy(image->image), *track);
630   *sector = block % apple35_sectors_per_track(imgtool_floppy(image->image), *track);
631   return IMGTOOLERR_SUCCESS;
632}
633
634
635
636/*
637   image_read_block()
638
639   Read one 512-byte block of data from a macintosh disk image
640
641   image (I/O): level-1 image reference
642   block (I): address of block to read
643   dest (O): buffer where block data should be stored
644
645   Return imgtool error code
646*/
647static imgtoolerr_t image_read_block(mac_l1_imgref *image, UINT32 block, void *dest)
648{
649   imgtoolerr_t err;
650   floperr_t ferr;
651   UINT32 track, head, sector;
652
653   err = mac_find_block(image, block, &track, &head, &sector);
654   if (err)
655      return err;
656
657   ferr = floppy_read_sector(imgtool_floppy(image->image), head, track, sector, 0, dest, 512);
658   if (ferr)
659      return imgtool_floppy_error(ferr);
660
661   return IMGTOOLERR_SUCCESS;
662}
663
664/*
665   image_write_block()
666
667   Read one 512-byte block of data from a macintosh disk image
668
669   image (I/O): level-1 image reference
670   block (I): address of block to write
671   src (I): buffer with the block data
672
673   Return imgtool error code
674*/
675static imgtoolerr_t image_write_block(mac_l1_imgref *image, UINT32 block, const void *src)
676{
677   imgtoolerr_t err;
678   floperr_t ferr;
679   UINT32 track, head, sector;
680
681   err = mac_find_block(image, block, &track, &head, &sector);
682   if (err)
683      return err;
684
685   ferr = floppy_write_sector(imgtool_floppy(image->image), head, track, sector, 0, src, 512);
686   if (ferr)
687      return imgtool_floppy_error(ferr);
688
689   return IMGTOOLERR_SUCCESS;
690}
691
692/*
693   image_get_tag_len()
694
695   Get length of tag data (12 for GCR floppies, 20 for HD20, 0 otherwise)
696
697   image (I/O): level-1 image reference
698
699   Return tag length
700*/
701INLINE int image_get_tag_len(mac_l1_imgref *image)
702{
703   return 0;
704}
705
706
707
708/*
709   image_read_tag()
710
711   Read a 12- or 20-byte tag record associated with a disk block
712
713   image (I/O): level-1 image reference
714   block (I): address of block to read
715   dest (O): buffer where tag data should be stored
716
717   Return imgtool error code
718*/
719static imgtoolerr_t image_read_tag(mac_l1_imgref *image, UINT32 block, void *dest)
720{
721   return IMGTOOLERR_UNEXPECTED;
722}
723
724/*
725   image_write_tag()
726
727   Write a 12- or 20-byte tag record associated with a disk block
728
729   image (I/O): level-1 image reference
730   block (I): address of block to write
731   src (I): buffer with the tag data
732
733   Return imgtool error code
734*/
735static imgtoolerr_t image_write_tag(mac_l1_imgref *image, UINT32 block, const void *src)
736{
737   return IMGTOOLERR_UNEXPECTED;
738}
739
740#if 0
741#pragma mark -
742#pragma mark MFS/HFS WRAPPERS
743#endif
744
745typedef enum
746{
747   L2I_MFS,
748   L2I_HFS
749} mac_format;
750
751typedef enum { data_fork = 0x00, rsrc_fork = 0xff } mac_forkID;
752
753typedef struct mac_l2_imgref mac_l2_imgref;
754
755/*
756   MFS image ref
757*/
758typedef struct mfs_l2_imgref
759{
760   UINT16 dir_num_files;
761   UINT16 dir_start;
762   UINT16 dir_blk_len;
763
764   UINT16 ABStart;
765
766   mac_str27 volname;
767
768   unsigned char ABlink_dirty[13];   /* dirty flag for each disk block in the ABlink array */
769   UINT8 ABlink[6141];
770} mfs_l2_imgref;
771
772/*
773   HFS extent descriptor
774*/
775typedef struct hfs_extent
776{
777   UINT16BE stABN;         /* first allocation block */
778   UINT16BE numABlks;      /* number of allocation blocks */
779} hfs_extent;
780
781/*
782   HFS likes to group extents by 3 (it is 8 with HFS+), so we create a
783   specific type.
784*/
785typedef hfs_extent hfs_extent_3[3];
786
787/*
788   MFS open file ref
789*/
790typedef struct mfs_fileref
791{
792   UINT16 stBlk;               /* first allocation block of file */
793} mfs_fileref;
794
795/*
796   HFS open file ref
797*/
798typedef struct hfs_fileref
799{
800   hfs_extent_3 extents;         /* first 3 file extents */
801
802   UINT32 parID;               /* CNID of parent directory (undefined for extent & catalog files) */
803   mac_str31 filename;            /* file name (undefined for extent & catalog files) */
804} hfs_fileref;
805
806/*
807   MFS/HFS open file ref
808*/
809typedef struct mac_fileref
810{
811   mac_l2_imgref *l2_img;         /* image pointer */
812
813   UINT32 fileID;               /* file ID (a.k.a. CNID in HFS/HFS+) */
814
815   mac_forkID forkType;         /* 0x00 for data, 0xff for resource */
816
817   UINT32 eof;                  /* logical end-of-file */
818   UINT32 pLen;               /* physical end-of-file */
819
820   UINT32 crPs;               /* current position in file */
821
822   UINT8 reload_buf;
823   UINT8 block_buffer[512];      /* buffer with current file block */
824
825   union
826   {
827      mfs_fileref mfs;
828      hfs_fileref hfs;
829   } u;
830} mac_fileref;
831
832/*
833   open BT ref
834*/
835typedef struct mac_BTref
836{
837   mac_fileref fileref;   /* open B-tree file ref */
838
839   UINT16 nodeSize;      /* size of a node, in bytes */
840   UINT32 rootNode;      /* node number of root node */
841   UINT32 firstLeafNode;   /* node number of first leaf node */
842   UINT32 attributes;      /* persistent attributes about the tree */
843   UINT16 treeDepth;      /* maximum height (usually leaf nodes) */
844   UINT16 maxKeyLength;   /* maximum key length */
845
846   /* function to compare keys during tree searches */
847   int (*key_compare_func)(const void *key1, const void *key2);
848
849   void *node_buf;         /* current node buffer */
850} mac_BTref;
851
852/*
853   Constants for BTHeaderRec attributes field
854*/
855enum
856{
857   btha_badCloseMask         = 0x00000001,   /* reserved */
858   btha_bigKeysMask         = 0x00000002,   /* key length field is 16 bits */
859   btha_variableIndexKeysMask   = 0x00000004   /* keys in index nodes are variable length */
860};
861
862/*
863   HFS image ref
864*/
865typedef struct hfs_l2_imgref
866{
867   UINT16 VBM_start;
868
869   UINT16 ABStart;
870
871   mac_str27 volname;
872
873   mac_BTref extents_BT;
874   mac_BTref cat_BT;
875
876   UINT8 VBM[8192];
877} hfs_l2_imgref;
878
879/*
880   MFS/HFS image ref
881*/
882struct mac_l2_imgref
883{
884   mac_l1_imgref l1_img;
885
886   UINT16 numABs;
887   UINT16 blocksperAB;
888
889   UINT16 freeABs;
890
891   UINT32 nxtCNID;      /* nxtFNum in MFS, nxtCNID in HFS */
892
893   mac_format format;
894   union
895   {
896      mfs_l2_imgref mfs;
897      hfs_l2_imgref hfs;
898   } u;
899};
900
901/*
902   MFS Master Directory Block
903*/
904typedef struct mfs_mdb
905{
906   UINT8    sigWord[2];   /* volume signature - always $D2D7 */
907   UINT32BE crDate;      /* date and time of volume creation */
908   UINT32BE lsMod/*lsBkUp???*/;/* date and time of last modification (backup???) */
909   UINT16BE atrb;         /* volume attributes (0x0000) */
910                        /* bit 15 is set if volume is locked by software */
911   UINT16BE nmFls;         /* number of files in directory */
912   UINT16BE dirSt;         /* first block of directory */
913
914   UINT16BE blLn;         /* length of directory in blocks (0x000C) */
915   UINT16BE nmAlBlks;      /* number of allocation blocks in volume (0x0187) */
916   UINT32BE alBlkSiz;      /* size (in bytes) of allocation blocks (0x00000400) */
917   UINT32BE clpSiz;      /* default clump size - number of bytes to allocate
918                        when a file grows (0x00002000) */
919   UINT16BE alBlSt;      /* first allocation block in volume (0x0010) */
920
921   UINT32BE nxtFNum;      /* next unused file number */
922   UINT16BE freeABs;      /* number of unused allocation blocks */
923
924   mac_str27 VN;         /* volume name */
925
926   UINT8    ABlink[512-64];/* Link array for file ABs.  Array of nmAlBlks
927                     12-bit-long entries, indexed by AB address.  If an
928                     AB belongs to no file, the entry is 0; if an AB is
929                     the last in any file, the entry is 1; if an AB
930                     belongs to a file and is not the last one, the
931                     entry is the AB address of the next file AB plus 1.
932                     Note that the array extends on as many consecutive
933                     disk blocks as needed (usually the MDB block plus
934                     the next one).  Incidentally, this array is not
935                     saved in the secondary MDB: presumably, the idea
936                     was that the disk utility could rely on the tag
937                     data to rebuild the link array if it should ever
938                     be corrupted. */
939} mfs_mdb;
940
941/*
942   HFS Master Directory Block
943*/
944typedef struct hfs_mdb
945{
946/* First fields are similar to MFS, though several fields have a different meaning */
947   UINT8    sigWord[2];   /* volume signature - always $D2D7 */
948   UINT32BE crDate;      /* date and time of volume creation */
949   UINT32BE lsMod;         /* date and time of last modification */
950   UINT16BE atrb;         /* volume attributes (0x0000) */
951                        /* bit 15 is set if volume is locked by software */
952   UINT16BE nmFls;         /* number of files in root folder */
953   UINT16BE VBMSt;         /* first block of volume bitmap */
954   UINT16BE allocPtr;      /* start of next allocation search */
955
956   UINT16BE nmAlBlks;      /* number of allocation blocks in volume */
957   UINT32BE alBlkSiz;      /* size (in bytes) of allocation blocks */
958   UINT32BE clpSiz;      /* default clump size - number of bytes to allocate
959                        when a file grows */
960   UINT16BE alBlSt;      /* first allocation block in volume (0x0010) */
961   UINT32BE nxtCNID;      /* next unused catalog node ID */
962   UINT16BE freeABs;      /* number of unused allocation blocks */
963   mac_str27 VN;         /* volume name */
964
965/* next fields are HFS-specific */
966
967   UINT32BE volBkUp;      /* date and time of last backup */
968   UINT16BE vSeqNum;      /* volume backup sequence number */
969   UINT32BE wrCnt;         /* volume write count */
970   UINT32BE xtClpSiz;      /* clump size for extents overflow file */
971   UINT32BE ctClpSiz;      /* clump size for catalog file */
972   UINT16BE nmRtDirs;      /* number of directories in root folder */
973   UINT32BE filCnt;      /* number of files in volume */
974   UINT32BE dirCnt;      /* number of directories in volume */
975   UINT8    fndrInfo[32];   /* information used by the Finder */
976
977   union
978   {
979      struct
980      {
981         UINT16BE VCSize;      /* size (in blocks) of volume cache */
982         UINT16BE VBMCSize;      /* size (in blocks) of volume bitmap cache */
983         UINT16BE ctlCSize;      /* size (in blocks) of common volume cache */
984      } v1;
985      struct
986      {
987         UINT16BE embedSigWord;   /* embedded volume signature */
988         hfs_extent embedExtent;   /* embedded volume location and size */
989      } v2;
990   } u;
991
992   UINT32BE xtFlSize;      /* size (in bytes) of extents overflow file */
993   hfs_extent_3 xtExtRec;   /* extent record for extents overflow file */
994   UINT32BE ctFlSize;      /* size (in bytes) of catalog file */
995   hfs_extent_3 ctExtRec;   /* extent record for catalog file */
996} hfs_mdb;
997
998/* to save a little stack space, we use the same buffer for MDB and next blocks */
999typedef union img_open_buf
1000{
1001   mfs_mdb mfs_mdb;
1002   hfs_mdb hfs_mdb;
1003   UINT8 raw[512];
1004} img_open_buf;
1005
1006/*
1007   Information extracted from catalog/directory
1008*/
1009typedef struct mac_dirent
1010{
1011   UINT16 dataRecType;         /* type of data record */
1012
1013   mac_FInfo flFinderInfo;      /* information used by the Finder */
1014   mac_FXInfo flXFinderInfo;   /* information used by the Finder */
1015
1016   UINT8  flags;            /* bit 0=1 if file locked */
1017
1018   UINT32 fileID;            /* file ID in directory/catalog */
1019
1020   UINT32 dataLogicalSize;      /* logical EOF of data fork */
1021   UINT32 dataPhysicalSize;   /* physical EOF of data fork */
1022   UINT32 rsrcLogicalSize;      /* logical EOF of resource fork */
1023   UINT32 rsrcPhysicalSize;   /* physical EOF of resource fork */
1024
1025   UINT32 createDate;         /* date and time of creation */
1026   UINT32 modifyDate;         /* date and time of last modification */
1027} mac_dirent;
1028
1029/*
1030   Tag record for GCR floppies (12 bytes)
1031
1032   And, no, I don't know the format of the 20-byte tag record of the HD20
1033*/
1034typedef struct floppy_tag_record
1035{
1036   UINT32BE fileID;         /* a.k.a. CNID */
1037                        /* a value of 1 seems to be the default for non-AB blocks, but this is not consistent */
1038   UINT8 ftype;            /* bit 1 = 1 if resource fork */
1039                        /* bit 0 = 1 if block is allocated to user file (i.e. it is not
1040                           in HFS extent & catalog, and not in non-AB blocks such
1041                           as MDB and MFS directory)??? */
1042                        /* bit 7 seems to be used, but I don't know what it means */
1043                        /* a value of $FF seems to be the default for non-AB blocks, but this is not consistent */
1044   UINT8 fattr;            /* bit 0 = 1 if locked(?) */
1045                        /* a value of $FF seems to be the default for non-AB blocks, but this is not consistent */
1046   UINT16BE fblock;         /* relative file block number (enough for any volume up to 32 MBytes in size) */
1047   UINT32BE wrCnt;            /* MFS: date and time of last write */
1048                        /* HFS: seems related to the wrCnt field in the mdb, i.e.
1049                           each time a volume is written to, the current value of
1050                           wrCnt is written in the tag field, then it is incremented */
1051                        /* (DV17 says "disk block number", but it cannot be true) */
1052} floppy_tag_record;
1053
1054#ifdef UNUSED_FUNCTION
1055static void hfs_image_close(mac_l2_imgref *l2_img);
1056#endif
1057static imgtoolerr_t mfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address);
1058static imgtoolerr_t hfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address);
1059static imgtoolerr_t mfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, mac_str255 filename, mac_dirent *cat_info, int create_it);
1060static imgtoolerr_t hfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, UINT32 *parID, mac_str255 filename, mac_dirent *cat_info);
1061static imgtoolerr_t mfs_file_open(mac_l2_imgref *l2_img, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref);
1062static imgtoolerr_t hfs_file_open(mac_l2_imgref *l2_img, UINT32 parID, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref);
1063static imgtoolerr_t mfs_file_setABeof(mac_fileref *fileref, UINT32 newABeof);
1064static imgtoolerr_t mfs_dir_update(mac_fileref *fileref);
1065
1066static mac_l2_imgref *get_imgref(imgtool_image *img)
1067{
1068   return (mac_l2_imgref *) imgtool_floppy_extrabytes(img);
1069}
1070
1071
1072#ifdef UNUSED_FUNCTION
1073/*
1074   mac_image_close
1075
1076   Close a macintosh image.
1077
1078   l2_img (I/O): level-2 image reference
1079*/
1080static void mac_image_close(mac_l2_imgref *l2_img)
1081{
1082   switch (l2_img->format)
1083   {
1084   case L2I_MFS:
1085      break;
1086
1087   case L2I_HFS:
1088      hfs_image_close(l2_img);
1089      break;
1090   }
1091}
1092#endif
1093
1094/*
1095   mac_lookup_path
1096
1097   Resolve a file path, and translate it to a parID + filename pair that enables
1098   to do an efficient file search on a HFS volume (and an inefficient one on
1099   MFS, but it is not an issue as MFS volumes typically have a few dozens
1100   files, vs. possibly thousands with HFS volumes).
1101
1102   l2_img (I/O): level-2 image reference
1103   fpath (I): file path (C string)
1104   parID (O): set to the CNID of the parent directory if the volume is in HFS
1105      format (reserved for MFS volumes)
1106   filename (O): set to the actual name of the file, with capitalization matching
1107      the one on the volume rather than the one in the fpath parameter (Mac
1108      string)
1109   cat_info (O): catalog info for this file extracted from the catalog file
1110      (may be NULL)
1111
1112   Return imgtool error code
1113*/
1114static imgtoolerr_t mac_lookup_path(mac_l2_imgref *l2_img, const char *fpath, UINT32 *parID, mac_str255 filename, mac_dirent *cat_info, int create_it)
1115{
1116   imgtoolerr_t err = IMGTOOLERR_UNEXPECTED;
1117
1118   switch (l2_img->format)
1119   {
1120      case L2I_MFS:
1121         *parID = 0;
1122         err = mfs_lookup_path(l2_img, fpath, filename, cat_info, create_it);
1123         break;
1124
1125      case L2I_HFS:
1126         err = hfs_lookup_path(l2_img, fpath, parID, filename, cat_info);
1127         break;
1128   }
1129   return err;
1130}
1131
1132/*
1133   mac_file_open
1134
1135   Open a file located on a macintosh image
1136
1137   l2_img (I/O): level-2 image reference
1138   parID (I): CNID of the parent directory if the volume is in HFS format
1139      (reserved for MFS volumes)
1140   filename (I): name of the file (Mac string)
1141   mac_forkID (I): tells which fork should be opened
1142   fileref (O): mac file reference to open
1143
1144   Return imgtool error code
1145*/
1146static imgtoolerr_t mac_file_open(mac_l2_imgref *l2_img, UINT32 parID, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref)
1147{
1148   switch (l2_img->format)
1149   {
1150   case L2I_MFS:
1151      return mfs_file_open(l2_img, filename, fork, fileref);
1152
1153   case L2I_HFS:
1154      return hfs_file_open(l2_img, parID, filename, fork, fileref);
1155   }
1156
1157   return IMGTOOLERR_UNEXPECTED;
1158}
1159
1160/*
1161   mac_file_read
1162
1163   Read data from an open mac file, starting at current position in file
1164
1165   fileref (I/O): mac file reference
1166   len (I): number of bytes to read
1167   dest (O): destination buffer
1168
1169   Return imgtool error code
1170*/
1171static imgtoolerr_t mac_file_read(mac_fileref *fileref, UINT32 len, void *dest)
1172{
1173   UINT32 block = 0;
1174   floppy_tag_record tag;
1175   int run_len;
1176   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1177
1178   if ((fileref->crPs + len) > fileref->eof)
1179      /* EOF */
1180      return IMGTOOLERR_UNEXPECTED;
1181
1182   while (len > 0)
1183   {
1184      if (fileref->reload_buf)
1185      {
1186         switch (fileref->l2_img->format)
1187         {
1188         case L2I_MFS:
1189            err = mfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1190            break;
1191
1192         case L2I_HFS:
1193            err = hfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1194            break;
1195         }
1196         if (err)
1197            return err;
1198         err = image_read_block(&fileref->l2_img->l1_img, block, fileref->block_buffer);
1199         if (err)
1200            return err;
1201         fileref->reload_buf = FALSE;
1202
1203         if (TAG_EXTRA_CHECKS)
1204         {
1205            /* optional check */
1206            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
1207            {
1208               err = image_read_tag(&fileref->l2_img->l1_img, block, &tag);
1209               if (err)
1210                  return err;
1211
1212               if ((get_UINT32BE(tag.fileID) != fileref->fileID)
1213                  || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
1214                  || (get_UINT16BE(tag.fblock) != ((fileref->crPs/512) & 0xffff)))
1215               {
1216                  return IMGTOOLERR_CORRUPTIMAGE;
1217               }
1218            }
1219         }
1220      }
1221      run_len = 512 - (fileref->crPs % 512);
1222      if (run_len > len)
1223         run_len = len;
1224
1225      memcpy(dest, fileref->block_buffer+(fileref->crPs % 512), run_len);
1226      len -= run_len;
1227      dest = (UINT8 *)dest + run_len;
1228      fileref->crPs += run_len;
1229      if ((fileref->crPs % 512) == 0)
1230         fileref->reload_buf = TRUE;
1231   }
1232
1233   return IMGTOOLERR_SUCCESS;
1234}
1235
1236/*
1237   mac_file_write
1238
1239   Write data to an open mac file, starting at current position in file
1240
1241   fileref (I/O): mac file reference
1242   len (I): number of bytes to read
1243   dest (O): destination buffer
1244
1245   Return imgtool error code
1246*/
1247static imgtoolerr_t mac_file_write(mac_fileref *fileref, UINT32 len, const void *src)
1248{
1249   UINT32 block = 0;
1250   floppy_tag_record tag;
1251   int run_len;
1252   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1253
1254   if ((fileref->crPs + len) > fileref->eof)
1255      /* EOF */
1256      return IMGTOOLERR_UNEXPECTED;
1257
1258   while (len > 0)
1259   {
1260      switch (fileref->l2_img->format)
1261      {
1262      case L2I_MFS:
1263         err = mfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1264         break;
1265
1266      case L2I_HFS:
1267         err = hfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1268         break;
1269      }
1270      if (err)
1271         return err;
1272
1273      if (TAG_CHECKS)
1274      {
1275         /* optional check */
1276         if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
1277         {
1278            err = image_read_tag(&fileref->l2_img->l1_img, block, &tag);
1279            if (err)
1280               return err;
1281
1282            if ((get_UINT32BE(tag.fileID) != fileref->fileID)
1283               || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
1284               || (get_UINT16BE(tag.fblock) != ((fileref->crPs/512) & 0xffff)))
1285            {
1286               return IMGTOOLERR_CORRUPTIMAGE;
1287            }
1288         }
1289      }
1290
1291      if (fileref->reload_buf)
1292      {
1293         err = image_read_block(&fileref->l2_img->l1_img, block, fileref->block_buffer);
1294         if (err)
1295            return err;
1296         fileref->reload_buf = FALSE;
1297      }
1298      run_len = 512 - (fileref->crPs % 512);
1299      if (run_len > len)
1300         run_len = len;
1301
1302      memcpy(fileref->block_buffer+(fileref->crPs % 512), src, run_len);
1303      err = image_write_block(&fileref->l2_img->l1_img, block, fileref->block_buffer);
1304      if (err)
1305         return err;
1306      /* update tag data */
1307      if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
1308      {
1309         if (!TAG_CHECKS)
1310         {
1311            err = image_read_tag(&fileref->l2_img->l1_img, block, &tag);
1312            if (err)
1313               return err;
1314         }
1315
1316         switch (fileref->l2_img->format)
1317         {
1318         case L2I_MFS:
1319            set_UINT32BE(&tag.wrCnt, mac_time_now());
1320            break;
1321
1322         case L2I_HFS:
1323            /*set_UINT32BE(&tag.wrCnt, ++fileref->l2_img.u.hfs.wrCnt);*/   /* ***TODO*** */
1324            break;
1325         }
1326
1327         err = image_write_tag(&fileref->l2_img->l1_img, block, &tag);
1328         if (err)
1329            return err;
1330      }
1331      len -= run_len;
1332      src = (const UINT8 *)src + run_len;
1333      fileref->crPs += run_len;
1334      if ((fileref->crPs % 512) == 0)
1335         fileref->reload_buf = TRUE;
1336   }
1337
1338   return IMGTOOLERR_SUCCESS;
1339}
1340
1341#ifdef UNUSED_FUNCTION
1342/*
1343   mac_file_tell
1344
1345   Get current position in an open mac file
1346
1347   fileref (I/O): mac file reference
1348   filePos (O): current position in file
1349
1350   Return imgtool error code
1351*/
1352static imgtoolerr_t mac_file_tell(mac_fileref *fileref, UINT32 *filePos)
1353{
1354   *filePos = fileref->crPs;
1355
1356   return IMGTOOLERR_SUCCESS;
1357}
1358#endif
1359
1360/*
1361   mac_file_seek
1362
1363   Set current position in an open mac file
1364
1365   fileref (I/O): mac file reference
1366   filePos (I): new position in file
1367
1368   Return imgtool error code
1369*/
1370static imgtoolerr_t mac_file_seek(mac_fileref *fileref, UINT32 filePos)
1371{
1372   if ((fileref->crPs / 512) != (filePos / 512))
1373      fileref->reload_buf = TRUE;
1374
1375   fileref->crPs = filePos;
1376
1377   return IMGTOOLERR_SUCCESS;
1378}
1379
1380/*
1381   mac_file_seteof
1382
1383   Set the position of the EOF in an open mac file
1384
1385   fileref (I/O): mac file reference
1386   newEof (I): new position of EOF in file
1387
1388   Return imgtool error code
1389*/
1390static imgtoolerr_t mac_file_seteof(mac_fileref *fileref, UINT32 newEof)
1391{
1392   UINT32 newABEof;
1393   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1394
1395   newABEof = (newEof + fileref->l2_img->blocksperAB * 512 - 1) / (fileref->l2_img->blocksperAB * 512);
1396
1397   /*if (fileref->pLen % (fileref->l2_img->blocksperAB * 512))
1398      return IMGTOOLERR_CORRUPTIMAGE;*/
1399
1400   if (newEof < fileref->eof)
1401      fileref->eof = newEof;
1402
1403   switch (fileref->l2_img->format)
1404   {
1405   case L2I_MFS:
1406      err = mfs_file_setABeof(fileref, newABEof);
1407      break;
1408
1409   case L2I_HFS:
1410      err = IMGTOOLERR_UNIMPLEMENTED;
1411      break;
1412   }
1413   if (err)
1414      return err;
1415
1416   fileref->eof = newEof;
1417
1418   err = mfs_dir_update(fileref);
1419   if (err)
1420      return err;
1421
1422   /* update current pos if beyond new EOF */
1423   /*if (fileref->crPs > newEof)
1424   {
1425      if ((fileref->crPs / 512) != (newEof / 512))
1426         fileref->reload_buf = TRUE;
1427
1428      fileref->crPs = newEof;
1429   }*/
1430
1431   return IMGTOOLERR_SUCCESS;
1432}
1433
1434#if 0
1435#pragma mark -
1436#pragma mark MFS IMPLEMENTATION
1437#endif
1438
1439/*
1440   directory entry for use in the directory file
1441
1442   Note the structure is variable length.  It is always word-aligned, and
1443   cannot cross block boundaries.
1444
1445   Note that the directory does not seem to be sorted: the order in which
1446   files appear does not match file names, and it does not always match file
1447   IDs.
1448*/
1449typedef struct mfs_dir_entry
1450{
1451   UINT8    flags;            /* bit 7=1 if entry used, bit 0=1 if file locked */
1452                        /* 0x00 means end of block: if we are not done
1453                        with reading the directory, the remnants will
1454                        be read from next block */
1455   UINT8    flVersNum;         /* version number (usually 0x00, but I don't
1456                           have the IM volume that describes it) */
1457   mac_FInfo flFinderInfo;      /* information used by the Finder */
1458
1459   UINT32BE fileID;         /* file ID */
1460
1461   UINT16BE dataStartBlock;   /* first allocation block of data fork */
1462   UINT32BE dataLogicalSize;   /* logical EOF of data fork */
1463   UINT32BE dataPhysicalSize;   /* physical EOF of data fork */
1464   UINT16BE rsrcStartBlock;   /* first allocation block of resource fork */
1465   UINT32BE rsrcLogicalSize;   /* logical EOF of resource fork */
1466   UINT32BE rsrcPhysicalSize;   /* physical EOF of resource fork */
1467
1468   UINT32BE createDate;      /* date and time of creation */
1469   UINT32BE modifyDate;      /* date and time of last modification */
1470
1471   UINT8    name[1];         /* first char is length of file name */
1472                        /* next chars are file name - 255 chars at most */
1473                        /* IIRC, Finder 7 only supports 31 chars,
1474                        wheareas earlier versions support 63 chars */
1475} mfs_dir_entry;
1476
1477/*
1478   FOBJ desktop resource: describes a folder, or the location of the volume
1479   icon.
1480
1481   In typical Apple manner, this resource is not documented.  However, I have
1482   managed to reverse engineer some parts of it.
1483*/
1484typedef struct mfs_FOBJ
1485{
1486   UINT8 unknown0[2];      /* $00: $0004 for disk, $0008 for folder??? */
1487   mac_point location;      /* $02: location in parent window */
1488   UINT8 unknown1[4];      /* $06: ??? */
1489   UINT8 view;            /* $0A: manner in which folders are displayed??? */
1490   UINT8 unknown2;         /* $0B: ??? */
1491   UINT16BE par_fldr;      /* $0C: parent folder ID */
1492   UINT8 unknown3[10];      /* $0E: ??? */
1493   UINT16BE unknown4;      /* $18: ??? */
1494   UINT32BE createDate;   /* $1A: date and time of creation */
1495   UINT32BE modifyDate;   /* $1E: date and time of last modification */
1496   UINT16BE unknown5;      /* $22: put-away folder ID?????? */
1497   UINT8 unknown6[8];      /* $24: ??? */
1498   mac_rect bounds;      /* $2C: window bounds */
1499   mac_point scroll;      /* $34: current scroll offset??? */
1500   union
1501   {   /* I think there are two versions of the structure */
1502      struct
1503      {
1504         UINT16BE item_count;   /* number of items (folders and files) in
1505                              this folder */
1506         UINT32BE item_descs[1];   /* this variable-length array has
1507                              item_count entries - meaning of entry is unknown */
1508      } v1;
1509      struct
1510      {
1511         UINT16BE zerofill;      /* always 0? */
1512         UINT16BE unknown0;      /* always 0??? */
1513         UINT16BE item_count;   /* number of items (folders and files) in
1514                              this folder */
1515         UINT8 unknown1[20];      /* ??? */
1516         UINT8 name[1];         /* variable-length macintosh string */
1517      } v2;
1518   } u;
1519} mfs_FOBJ;
1520
1521/*
1522   MFS open dir ref
1523*/
1524typedef struct mfs_dirref
1525{
1526   mac_l2_imgref *l2_img;         /* image pointer */
1527   UINT16 index;               /* current file index in the disk directory */
1528   UINT16 cur_block;            /* current block offset in directory file */
1529   UINT16 cur_offset;            /* current byte offset in current block of directory file */
1530   UINT8 block_buffer[512];      /* buffer with current directory block */
1531} mfs_dirref;
1532
1533
1534
1535static imgtoolerr_t mfs_image_create(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
1536{
1537   imgtoolerr_t err;
1538   UINT8 buffer[512];
1539   UINT32 heads, tracks, sector_bytes, i;
1540   UINT32 total_disk_blocks, total_allocation_blocks, allocation_block_size;
1541   UINT32 free_allocation_blocks;
1542
1543   heads = option_resolution_lookup_int(opts, 'H');
1544   tracks = option_resolution_lookup_int(opts, 'T');
1545   sector_bytes = option_resolution_lookup_int(opts, 'L');
1546
1547   get_imgref(image)->l1_img.image = image;
1548   get_imgref(image)->l1_img.heads = heads;
1549
1550   if (sector_bytes != 512)
1551      return IMGTOOLERR_UNEXPECTED;
1552
1553   /* computation */
1554   allocation_block_size = 1024;
1555   total_disk_blocks = 0;
1556   for (i = 0; i < tracks; i++)
1557      total_disk_blocks += heads * apple35_sectors_per_track(imgtool_floppy(image), i) * sector_bytes / 512;
1558   total_allocation_blocks = total_disk_blocks / (allocation_block_size / 512);
1559   free_allocation_blocks = total_allocation_blocks - 3;
1560
1561   /* write master directory block */
1562   memset(buffer, 0, sizeof(buffer));
1563   place_integer_be(buffer,  0, 2, 0xd2d7);               /* signature */
1564   place_integer_be(buffer,  2, 4, mac_time_now());         /* creation date */
1565   place_integer_be(buffer,  6, 4, mac_time_now());         /* last modified date */
1566   place_integer_be(buffer, 10, 2, 0);                     /* volume attributes */
1567   place_integer_be(buffer, 12, 2, 0);                     /* number of files in directory */
1568   place_integer_be(buffer, 14, 2, 4);                     /* first block of directory */
1569   place_integer_be(buffer, 16, 2, 12);                  /* length of directory in blocks */
1570   place_integer_be(buffer, 18, 2, total_allocation_blocks);   /* allocation blocks on volume count */
1571   place_integer_be(buffer, 20, 4, allocation_block_size);      /* allocation block size */
1572   place_integer_be(buffer, 24, 4, 8192);                  /* default clumping size */
1573   place_integer_be(buffer, 28, 2, 16);                  /* first allocation block on volume */
1574   place_integer_be(buffer, 30, 4, 2);                     /* next unused catalog node */
1575   place_integer_be(buffer, 34, 2, free_allocation_blocks);   /* free allocation block count */
1576   pascal_from_c_string(&buffer[36], 28, "Untitled");         /* volume title */
1577
1578   err = image_write_block(&get_imgref(image)->l1_img, 2, buffer);
1579   if (err)
1580      return err;
1581
1582   return IMGTOOLERR_SUCCESS;
1583}
1584
1585
1586
1587/*
1588   mfs_image_open
1589
1590   Open a MFS image.  Image must already be open on level 1.  This function
1591   should not be called directly: call mac_image_open() instead.
1592
1593   l2_img (I/O): level-2 image reference to open (l1_img and format fields
1594      must be initialized)
1595   img_open_buf (I): buffer with the MDB block
1596
1597   Return imgtool error code
1598*/
1599static imgtoolerr_t mfs_image_open(imgtool_image *image, imgtool_stream *stream)
1600{
1601   imgtoolerr_t err;
1602   mac_l2_imgref *l2_img;
1603   img_open_buf buf_local;
1604   img_open_buf *buf;
1605
1606   l2_img = get_imgref(image);
1607   l2_img->l1_img.image = image;
1608   l2_img->l1_img.heads = 1;
1609   l2_img->format = L2I_MFS;
1610
1611   /* read MDB */
1612   err = image_read_block(&l2_img->l1_img, 2, &buf_local.raw);
1613   if (err)
1614      return err;
1615   buf = &buf_local;
1616
1617   /* check signature word */
1618   if ((buf->mfs_mdb.sigWord[0] != 0xd2) || (buf->mfs_mdb.sigWord[1] != 0xd7)
1619         || (buf->mfs_mdb.VN[0] > 27))
1620      return IMGTOOLERR_CORRUPTIMAGE;
1621
1622   l2_img->u.mfs.dir_num_files = get_UINT16BE(buf->mfs_mdb.nmFls);
1623   l2_img->u.mfs.dir_start = get_UINT16BE(buf->mfs_mdb.dirSt);
1624   l2_img->u.mfs.dir_blk_len = get_UINT16BE(buf->mfs_mdb.blLn);
1625
1626   l2_img->numABs = get_UINT16BE(buf->mfs_mdb.nmAlBlks);
1627   if ((get_UINT32BE(buf->mfs_mdb.alBlkSiz) % 512) || (get_UINT32BE(buf->mfs_mdb.alBlkSiz) == 0))
1628      return IMGTOOLERR_CORRUPTIMAGE;
1629   l2_img->blocksperAB = get_UINT32BE(buf->mfs_mdb.alBlkSiz) / 512;
1630   l2_img->u.mfs.ABStart = get_UINT16BE(buf->mfs_mdb.alBlSt);
1631
1632   l2_img->nxtCNID = get_UINT32BE(buf->mfs_mdb.nxtFNum);
1633
1634   l2_img->freeABs = get_UINT16BE(buf->mfs_mdb.freeABs);
1635
1636   mac_strcpy(l2_img->u.mfs.volname, buf->mfs_mdb.VN);
1637
1638   if (l2_img->numABs > 4094)
1639      return IMGTOOLERR_CORRUPTIMAGE;
1640
1641   /* extract link array */
1642   {
1643      int byte_len = l2_img->numABs + ((l2_img->numABs + 1) >> 1);
1644      int cur_byte;
1645      int cur_block;
1646      int block_len = sizeof(buf->mfs_mdb.ABlink);
1647
1648      /* clear dirty flags */
1649      for (cur_block=0; cur_block<13; cur_block++)
1650         l2_img->u.mfs.ABlink_dirty[cur_block] = 0;
1651
1652      /* append the chunk after MDB to link array */
1653      cur_byte = 0;
1654      if (block_len > (byte_len - cur_byte))
1655         block_len = byte_len - cur_byte;
1656      memcpy(l2_img->u.mfs.ABlink+cur_byte, buf->mfs_mdb.ABlink, block_len);
1657      cur_byte += block_len;
1658      cur_block = 2;
1659      while (cur_byte < byte_len)
1660      {
1661         /* read next block */
1662         cur_block++;
1663         err = image_read_block(&l2_img->l1_img, cur_block, buf->raw);
1664         if (err)
1665            return err;
1666         block_len = 512;
1667
1668         /* append this block to link array */
1669         if (block_len > (byte_len - cur_byte))
1670            block_len = byte_len - cur_byte;
1671         memcpy(l2_img->u.mfs.ABlink+cur_byte, buf->raw, block_len);
1672         cur_byte += block_len;
1673      }
1674      /* check that link array and directory don't overlap */
1675      if (cur_block >= l2_img->u.mfs.dir_start)
1676         return IMGTOOLERR_CORRUPTIMAGE;
1677   }
1678
1679   return IMGTOOLERR_SUCCESS;
1680}
1681
1682/*
1683   mfs_update_mdb
1684
1685   Update MDB on disk
1686
1687   l2_img (I/O): level-2 image reference
1688
1689   Return imgtool error code
1690*/
1691static imgtoolerr_t mfs_update_mdb(mac_l2_imgref *l2_img)
1692{
1693   imgtoolerr_t err;
1694   union
1695   {
1696      mfs_mdb mfs_mdb;
1697      UINT8 raw[512];
1698   } buf;
1699
1700   assert(l2_img->format == L2I_MFS);
1701
1702   /* read MDB */
1703   err = image_read_block(&l2_img->l1_img, 2, &buf.mfs_mdb);
1704   if (err)
1705      return err;
1706
1707   set_UINT16BE(&buf.mfs_mdb.nmFls, l2_img->u.mfs.dir_num_files);
1708#if 0   /* these fields are never changed */
1709   set_UINT16BE(&buf.mfs_mdb.dirSt, l2_img->u.mfs.dir_start);
1710   set_UINT16BE(&buf.mfs_mdb.blLn, l2_img->u.mfs.dir_blk_len);
1711
1712   set_UINT16BE(&buf.mfs_mdb.nmAlBlks, l2_img->numABs);
1713   set_UINT32BE(&buf.mfs_mdb.alBlkSiz, l2_img->blocksperAB*512);
1714   set_UINT16BE(&buf.mfs_mdb.alBlSt, l2_img->u.mfs.ABStart);
1715#endif
1716
1717   set_UINT32BE(&buf.mfs_mdb.nxtFNum, l2_img->nxtCNID);
1718
1719   set_UINT16BE(&buf.mfs_mdb.freeABs, l2_img->freeABs);
1720
1721#if 0   /* these fields are never changed */
1722   mac_strcpy(buf.mfs_mdb.VN, l2_img->u.mfs.volname);
1723#endif
1724
1725   /* save link array */
1726   {
1727      int byte_len = l2_img->numABs + ((l2_img->numABs + 1) >> 1);
1728      int cur_byte = 0;
1729      int cur_block = 2;
1730      int block_len = sizeof(buf.mfs_mdb.ABlink);
1731
1732      /* update the chunk of link array after the MDB */
1733      if (block_len > (byte_len - cur_byte))
1734         block_len = byte_len - cur_byte;
1735      memcpy(buf.mfs_mdb.ABlink, l2_img->u.mfs.ABlink+cur_byte, block_len);
1736      cur_byte += block_len;
1737
1738      if (block_len < sizeof(buf.mfs_mdb.ABlink))
1739         memset(buf.mfs_mdb.ABlink+block_len, 0, sizeof(buf.mfs_mdb.ABlink)-block_len);
1740
1741      l2_img->u.mfs.ABlink_dirty[0] = 0;
1742
1743      /* write back modified MDB+link */
1744      err = image_write_block(&l2_img->l1_img, 2, &buf.mfs_mdb);
1745      if (err)
1746         return err;
1747
1748      while (cur_byte < byte_len)
1749      {
1750         /* advance to next block */
1751         cur_block++;
1752         block_len = 512;
1753
1754         /* extract the current chunk of link array */
1755         if (block_len > (byte_len - cur_byte))
1756            block_len = byte_len - cur_byte;
1757
1758         if (l2_img->u.mfs.ABlink_dirty[cur_block-2])
1759         {
1760            memcpy(buf.raw, l2_img->u.mfs.ABlink+cur_byte, block_len);
1761            if (block_len < 512)
1762               memset(buf.raw+block_len, 0, 512-block_len);
1763            /* write back link array */
1764            err = image_write_block(&l2_img->l1_img, cur_block, buf.raw);
1765            if (err)
1766               return err;
1767            l2_img->u.mfs.ABlink_dirty[cur_block-2] = 0;
1768         }
1769
1770         cur_byte += block_len;
1771      }
1772   }
1773
1774   return IMGTOOLERR_SUCCESS;
1775}
1776
1777/*
1778   mfs_dir_open
1779
1780   Open the directory file
1781
1782   l2_img (I/O): level-2 image reference
1783   dirref (O): open directory file reference
1784
1785   Return imgtool error code
1786*/
1787static imgtoolerr_t mfs_dir_open(mac_l2_imgref *l2_img, const char *path, mfs_dirref *dirref)
1788{
1789   imgtoolerr_t err;
1790
1791   assert(l2_img->format == L2I_MFS);
1792
1793   if (path[0])
1794      return IMGTOOLERR_PATHNOTFOUND;
1795
1796   dirref->l2_img = l2_img;
1797   dirref->index = 0;
1798
1799   dirref->cur_block = 0;
1800   dirref->cur_offset = 0;
1801   err = image_read_block(&l2_img->l1_img, l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1802   if (err)
1803      return err;
1804
1805   return IMGTOOLERR_SUCCESS;
1806}
1807
1808/*
1809   mfs_dir_read
1810
1811   Read one entry of directory file
1812
1813   dirref (I/O): open directory file reference
1814   dir_entry (O): set to point to the entry read: set to NULL if EOF or error
1815
1816   Return imgtool error code
1817*/
1818static imgtoolerr_t mfs_dir_read(mfs_dirref *dirref, mfs_dir_entry **dir_entry)
1819{
1820   mfs_dir_entry *cur_dir_entry;
1821   size_t cur_dir_entry_len;
1822   imgtoolerr_t err;
1823
1824
1825   if (dir_entry)
1826      *dir_entry = NULL;
1827
1828   if (dirref->index == dirref->l2_img->u.mfs.dir_num_files)
1829      /* EOF */
1830      return IMGTOOLERR_SUCCESS;
1831
1832   /* get cat entry pointer */
1833   cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1834   while ((dirref->cur_offset == 512) || ! (cur_dir_entry->flags & 0x80))
1835   {
1836      dirref->cur_block++;
1837      dirref->cur_offset = 0;
1838      if (dirref->cur_block > dirref->l2_img->u.mfs.dir_blk_len)
1839         /* aargh! */
1840         return IMGTOOLERR_CORRUPTIMAGE;
1841      err = image_read_block(&dirref->l2_img->l1_img, dirref->l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1842      if (err)
1843         return err;
1844      cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1845   }
1846
1847   cur_dir_entry_len = offsetof(mfs_dir_entry, name) + cur_dir_entry->name[0] + 1;
1848
1849   if ((dirref->cur_offset + cur_dir_entry_len) > 512)
1850      /* aargh! */
1851      return IMGTOOLERR_CORRUPTIMAGE;
1852
1853   /* entry looks valid: set pointer to entry */
1854   if (dir_entry)
1855      *dir_entry = cur_dir_entry;
1856
1857   /* update offset in block */
1858   dirref->cur_offset += cur_dir_entry_len;
1859   /* align to word boundary */
1860   dirref->cur_offset = (dirref->cur_offset + 1) & ~1;
1861
1862   /* update file count */
1863   dirref->index++;
1864
1865   return IMGTOOLERR_SUCCESS;
1866}
1867
1868/*
1869   mfs_dir_insert
1870
1871   Add an entry in the directory file
1872
1873   l2_img (I/O): level-2 image reference
1874   dirref (I/O): open directory file reference
1875   filename (I): name of the file for which an entry is created (Mac string)
1876   dir_entry (O): set to point to the created entry: set to NULL if EOF or
1877      error
1878
1879   Return imgtool error code
1880*/
1881static imgtoolerr_t mfs_dir_insert(mac_l2_imgref *l2_img, mfs_dirref *dirref, const UINT8 *new_fname, mfs_dir_entry **dir_entry)
1882{
1883   size_t new_dir_entry_len;
1884   mfs_dir_entry *cur_dir_entry;
1885   size_t cur_dir_entry_len;
1886   UINT32 cur_date;
1887   imgtoolerr_t err;
1888
1889   dirref->l2_img = l2_img;
1890   dirref->index = 0;
1891
1892   new_dir_entry_len = offsetof(mfs_dir_entry, name) + new_fname[0] + 1;
1893
1894   for (dirref->cur_block = 0; dirref->cur_block < dirref->l2_img->u.mfs.dir_blk_len; dirref->cur_block++)
1895   {
1896      /* read current block */
1897      err = image_read_block(&dirref->l2_img->l1_img, dirref->l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1898      if (err)
1899         return err;
1900
1901      /* get free chunk in this block */
1902      dirref->cur_offset = 0;
1903      cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1904      while ((dirref->cur_offset < 512) && (cur_dir_entry->flags & 0x80))
1905      {   /* skip cur_dir_entry */
1906         cur_dir_entry_len = offsetof(mfs_dir_entry, name) + cur_dir_entry->name[0] + 1;
1907         /* update offset in block */
1908         dirref->cur_offset += cur_dir_entry_len;
1909         /* align to word boundary */
1910         dirref->cur_offset = (dirref->cur_offset + 1) & ~1;
1911         /* update entry pointer */
1912         cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1913         /* update file index (useless, but can't harm) */
1914         dirref->index++;
1915      }
1916
1917      if (new_dir_entry_len <= (/*512*/510 - dirref->cur_offset))
1918      {
1919         /*memcpy(cur_dir_entry, new_dir_entry, new_dir_entry_len);*/
1920         cur_dir_entry->flags = 0x80;
1921         cur_dir_entry->flVersNum = 0x00;
1922         memset(&cur_dir_entry->flFinderInfo, 0, sizeof(cur_dir_entry->flFinderInfo));
1923         set_UINT32BE(&cur_dir_entry->fileID, dirref->l2_img->nxtCNID++);
1924         set_UINT16BE(&cur_dir_entry->dataStartBlock, 1);
1925         set_UINT32BE(&cur_dir_entry->dataLogicalSize, 0);
1926         set_UINT32BE(&cur_dir_entry->dataPhysicalSize, 0);
1927         set_UINT16BE(&cur_dir_entry->rsrcStartBlock, 1);
1928         set_UINT32BE(&cur_dir_entry->rsrcLogicalSize, 0);
1929         set_UINT32BE(&cur_dir_entry->rsrcPhysicalSize, 0);
1930         cur_date = mac_time_now();
1931         set_UINT32BE(&cur_dir_entry->createDate, cur_date);
1932         set_UINT32BE(&cur_dir_entry->modifyDate, cur_date);
1933         mac_strcpy(cur_dir_entry->name, new_fname);
1934
1935         /* update offset in block */
1936         dirref->cur_offset += new_dir_entry_len;
1937         /* align to word boundary */
1938         dirref->cur_offset = (dirref->cur_offset + 1) & ~1;
1939         if (dirref->cur_offset < 512)
1940            /* mark remaining space as free record */
1941            dirref->block_buffer[dirref->cur_offset] = 0;
1942         /* write back directory */
1943         err = image_write_block(&dirref->l2_img->l1_img, dirref->l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1944         if (err)
1945            return err;
1946         /* update file count */
1947         dirref->l2_img->u.mfs.dir_num_files++;
1948
1949         /* update MDB (nxtCNID & dir_num_files fields) */
1950         err = mfs_update_mdb(dirref->l2_img);
1951         if (err)
1952            return err;
1953
1954         if (dir_entry)
1955            *dir_entry = cur_dir_entry;
1956         return IMGTOOLERR_SUCCESS;
1957      }
1958   }
1959
1960   return IMGTOOLERR_NOSPACE;
1961}
1962
1963/*
1964   mfs_dir_update
1965
1966   Update one entry of directory file
1967
1968   fileref (I/O): open file reference
1969
1970   Return imgtool error code
1971*/
1972static imgtoolerr_t mfs_dir_update(mac_fileref *fileref)
1973{
1974   UINT16 cur_block;
1975   UINT16 cur_offset;
1976   UINT8 block_buffer[512];
1977   mfs_dir_entry *cur_dir_entry;
1978   size_t cur_dir_entry_len;
1979   imgtoolerr_t err;
1980
1981   for (cur_block = 0; cur_block < fileref->l2_img->u.mfs.dir_blk_len; cur_block++)
1982   {
1983      /* read current block */
1984      err = image_read_block(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.dir_start + cur_block, block_buffer);
1985      if (err)
1986         return err;
1987
1988      /* get free chunk in this block */
1989      cur_offset = 0;
1990      cur_dir_entry = (mfs_dir_entry *) (block_buffer + cur_offset);
1991      while ((cur_offset < 512) && (cur_dir_entry->flags & 0x80))
1992      {
1993         if (get_UINT32BE(cur_dir_entry->fileID) == fileref->fileID)
1994         {   /* found it: update directory entry */
1995            switch (fileref->forkType)
1996            {
1997            case data_fork:
1998               set_UINT16BE(&cur_dir_entry->dataStartBlock, fileref->u.mfs.stBlk);
1999               set_UINT32BE(&cur_dir_entry->dataLogicalSize, fileref->eof);
2000               set_UINT32BE(&cur_dir_entry->dataPhysicalSize, fileref->pLen);
2001               break;
2002
2003            case rsrc_fork:
2004               set_UINT16BE(&cur_dir_entry->rsrcStartBlock, fileref->u.mfs.stBlk);
2005               set_UINT32BE(&cur_dir_entry->rsrcLogicalSize, fileref->eof);
2006               set_UINT32BE(&cur_dir_entry->rsrcPhysicalSize, fileref->pLen);
2007               break;
2008            }
2009            /* write back directory */
2010            err = image_write_block(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.dir_start + cur_block, block_buffer);
2011            if (err)
2012               return err;
2013
2014            return IMGTOOLERR_SUCCESS;
2015         }
2016         /* skip cur_dir_entry */
2017         cur_dir_entry_len = offsetof(mfs_dir_entry, name) + cur_dir_entry->name[0] + 1;
2018         /* update offset in block */
2019         cur_offset += cur_dir_entry_len;
2020         /* align to word boundary */
2021         cur_offset = (cur_offset + 1) & ~1;
2022         /* update entry pointer */
2023         cur_dir_entry = (mfs_dir_entry *) (block_buffer + cur_offset);
2024      }
2025   }
2026
2027   return IMGTOOLERR_UNEXPECTED;
2028}
2029
2030
2031/*
2032   mfs_find_dir_entry
2033
2034   Find a file in an MFS directory
2035
2036   dirref (I/O): open directory file reference
2037   filename (I): file name (Mac string)
2038   dir_entry (O): set to point to the entry read: set to NULL if EOF or error
2039
2040   Return imgtool error code
2041*/
2042static imgtoolerr_t mfs_find_dir_entry(mfs_dirref *dirref, const mac_str255 filename, mfs_dir_entry **dir_entry)
2043{
2044   mfs_dir_entry *cur_dir_entry;
2045   imgtoolerr_t err;
2046
2047   if (dir_entry)
2048      *dir_entry = NULL;
2049
2050   /*  scan dir for file */
2051   while (1)
2052   {
2053      err = mfs_dir_read(dirref, &cur_dir_entry);
2054      if (err)
2055         return err;
2056      if (!cur_dir_entry)
2057         /* EOF */
2058         break;
2059      if ((! mac_stricmp(filename, cur_dir_entry->name)) && (cur_dir_entry->flVersNum == 0))
2060      {   /* file found */
2061
2062         if (dir_entry)
2063            *dir_entry = cur_dir_entry;
2064
2065         return IMGTOOLERR_SUCCESS;
2066      }
2067   }
2068
2069   return IMGTOOLERR_FILENOTFOUND;
2070}
2071
2072/*
2073   mfs_lookup_path
2074
2075   Resolve a file path for MFS volumes.  This function should not be called
2076   directly: call mac_lookup_path instead.
2077
2078   l2_img (I/O): level-2 image reference
2079   fpath (I): file path (C string)
2080   filename (O): set to the actual name of the file, with capitalization matching
2081      the one on the volume rather than the one in the fpath parameter (Mac
2082      string)
2083   cat_info (I/O): on output, catalog info for this file extracted from the
2084      catalog file (may be NULL)
2085      If create_it is TRUE, created info will first be set according to the
2086      data from cat_info
2087   create_it (I): TRUE if entry should be created if not found
2088
2089   Return imgtool error code
2090*/
2091static imgtoolerr_t mfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, mac_str255 filename, mac_dirent *cat_info, int create_it)
2092{
2093   mfs_dirref dirref;
2094   mfs_dir_entry *dir_entry;
2095   imgtoolerr_t err;
2096
2097   /* rapid check */
2098   if (strchr(fpath, ':'))
2099      return IMGTOOLERR_BADFILENAME;
2100
2101   /* extract file name */
2102   c_to_mac_strncpy(filename, fpath, strlen(fpath));
2103
2104   /* open dir */
2105   mfs_dir_open(l2_img, "", &dirref);
2106
2107   /* find file */
2108   err = mfs_find_dir_entry(&dirref, filename, &dir_entry);
2109   if ((err == IMGTOOLERR_FILENOTFOUND) && create_it)
2110      err = mfs_dir_insert(l2_img, &dirref, filename, &dir_entry);
2111   if (err)
2112      return err;
2113
2114   mac_strcpy(filename, dir_entry->name);
2115
2116   if (create_it && cat_info)
2117   {
2118      dir_entry->flFinderInfo = cat_info->flFinderInfo;
2119      dir_entry->flags = (dir_entry->flags & 0x80) | (cat_info->flags & 0x7f);
2120      set_UINT32BE(&dir_entry->createDate, cat_info->createDate);
2121      set_UINT32BE(&dir_entry->modifyDate, cat_info->modifyDate);
2122
2123      /* write current directory block */
2124      err = image_write_block(&l2_img->l1_img, l2_img->u.mfs.dir_start + dirref.cur_block, dirref.block_buffer);
2125      if (err)
2126         return err;
2127   }
2128
2129   if (cat_info)
2130   {
2131      cat_info->flFinderInfo = dir_entry->flFinderInfo;
2132      memset(&cat_info->flXFinderInfo, 0, sizeof(cat_info->flXFinderInfo));
2133      cat_info->flags = dir_entry->flags;
2134      cat_info->fileID = get_UINT32BE(dir_entry->fileID);
2135      cat_info->dataLogicalSize = get_UINT32BE(dir_entry->dataLogicalSize);
2136      cat_info->dataPhysicalSize = get_UINT32BE(dir_entry->dataPhysicalSize);
2137      cat_info->rsrcLogicalSize = get_UINT32BE(dir_entry->rsrcLogicalSize);
2138      cat_info->rsrcPhysicalSize = get_UINT32BE(dir_entry->rsrcPhysicalSize);
2139      cat_info->createDate = get_UINT32BE(dir_entry->createDate);
2140      cat_info->modifyDate = get_UINT32BE(dir_entry->modifyDate);
2141      cat_info->dataRecType = 0x200; /* hcrt_File */
2142   }
2143
2144   return IMGTOOLERR_SUCCESS;
2145}
2146
2147/*
2148   mfs_file_open_internal
2149
2150   Open a file fork, given its directory entry.  This function should not be
2151   called directly: call mfs_file_open instead.
2152
2153   l2_img (I/O): level-2 image reference
2154   dir_entry (I): directory entry for the file to open
2155   mac_forkID (I): tells which fork should be opened
2156   fileref (O): mac file reference to open
2157
2158   Return imgtool error code
2159*/
2160static imgtoolerr_t mfs_file_open_internal(mac_l2_imgref *l2_img, const mfs_dir_entry *dir_entry, mac_forkID fork, mac_fileref *fileref)
2161{
2162   assert(l2_img->format == L2I_MFS);
2163
2164   fileref->l2_img = l2_img;
2165
2166   fileref->fileID = get_UINT32BE(dir_entry->fileID);
2167   fileref->forkType = fork;
2168
2169   switch (fork)
2170   {
2171   case data_fork:
2172      fileref->u.mfs.stBlk = get_UINT16BE(dir_entry->dataStartBlock);
2173      fileref->eof = get_UINT32BE(dir_entry->dataLogicalSize);
2174      fileref->pLen = get_UINT32BE(dir_entry->dataPhysicalSize);
2175      break;
2176
2177   case rsrc_fork:
2178      fileref->u.mfs.stBlk = get_UINT16BE(dir_entry->rsrcStartBlock);
2179      fileref->eof = get_UINT32BE(dir_entry->rsrcLogicalSize);
2180      fileref->pLen = get_UINT32BE(dir_entry->rsrcPhysicalSize);
2181      break;
2182   }
2183
2184   fileref->crPs = 0;
2185
2186   fileref->reload_buf = TRUE;
2187
2188   return IMGTOOLERR_SUCCESS;
2189}
2190
2191/*
2192   mfs_file_open
2193
2194   Open a file located on a MFS volume.  This function should not be called
2195   directly: call mac_file_open instead.
2196
2197   l2_img (I/O): level-2 image reference
2198   filename (I): name of the file (Mac string)
2199   mac_forkID (I): tells which fork should be opened
2200   fileref (O): mac file reference to open
2201
2202   Return imgtool error code
2203*/
2204static imgtoolerr_t mfs_file_open(mac_l2_imgref *l2_img, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref)
2205{
2206   mfs_dirref dirref;
2207   mfs_dir_entry *dir_entry;
2208   imgtoolerr_t err;
2209
2210   /* open dir */
2211   mfs_dir_open(l2_img, "", &dirref);
2212
2213   /* find file */
2214   err = mfs_find_dir_entry(&dirref, filename, &dir_entry);
2215   if (err)
2216      return err;
2217
2218   /* open it */
2219   return mfs_file_open_internal(l2_img, dir_entry, fork, fileref);
2220}
2221
2222/*
2223   mfs_get_ABlink
2224
2225   Read one entry of the Allocation Bitmap link array, on an MFS volume.
2226
2227   l2_img (I/O): level-2 image reference
2228   AB_address (I): index in the array, which is an AB address
2229
2230   Returns the 12-bit value read in array.
2231*/
2232static UINT16 mfs_get_ABlink(mac_l2_imgref *l2_img, UINT16 AB_address)
2233{
2234   UINT16 reply;
2235   int base;
2236
2237   assert(l2_img->format == L2I_MFS);
2238
2239   base = (AB_address >> 1) * 3;
2240
2241   if (! (AB_address & 1))
2242      reply = (l2_img->u.mfs.ABlink[base] << 4) | ((l2_img->u.mfs.ABlink[base+1] >> 4) & 0x0f);
2243   else
2244      reply = ((l2_img->u.mfs.ABlink[base+1] << 8) & 0xf00) | l2_img->u.mfs.ABlink[base+2];
2245
2246   return reply;
2247}
2248
2249/*
2250   mfs_set_ABlink
2251
2252   Set one entry of the Allocation Bitmap link array, on an MFS volume.
2253
2254   l2_img (I/O): level-2 image reference
2255   AB_address (I): index in the array, which is an AB address
2256   data (I): 12-bit value to write in array
2257*/
2258static void mfs_set_ABlink(mac_l2_imgref *l2_img, UINT16 AB_address, UINT16 data)
2259{
2260   int base;
2261
2262   assert(l2_img->format == L2I_MFS);
2263
2264   base = (AB_address >> 1) * 3;
2265
2266   if (! (AB_address & 1))
2267   {
2268      l2_img->u.mfs.ABlink[base] = (data >> 4) & 0xff;
2269      l2_img->u.mfs.ABlink[base+1] = (l2_img->u.mfs.ABlink[base+1] & 0x0f) | ((data << 4) & 0xf0);
2270
2271      l2_img->u.mfs.ABlink_dirty[(base+64)/512] = 1;
2272      l2_img->u.mfs.ABlink_dirty[(base+1+64)/512] = 1;
2273   }
2274   else
2275   {
2276      l2_img->u.mfs.ABlink[base+1] = (l2_img->u.mfs.ABlink[base+1] & 0xf0) | ((data >> 8) & 0x0f);
2277      l2_img->u.mfs.ABlink[base+2] = data & 0xff;
2278
2279      l2_img->u.mfs.ABlink_dirty[(base+1+64)/512] = 1;
2280      l2_img->u.mfs.ABlink_dirty[(base+2+64)/512] = 1;
2281   }
2282}
2283
2284/*
2285   mfs_file_get_nth_block_address
2286
2287   Get the disk block address of a given block in an open file on a MFS image.
2288   Called by macintosh file code.
2289
2290   fileref (I/O): open mac file reference
2291   block_num (I): file block index
2292   block_address (O): disk block address for the file block
2293
2294   Return imgtool error code
2295*/
2296static imgtoolerr_t mfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address)
2297{
2298   UINT32 AB_num;
2299   UINT32 i;
2300   UINT16 AB_address;
2301
2302   assert(fileref->l2_img->format == L2I_MFS);
2303
2304   AB_num = block_num / fileref->l2_img->blocksperAB;
2305
2306   AB_address = fileref->u.mfs.stBlk;
2307   if ((AB_address == 0) || (AB_address >= fileref->l2_img->numABs+2))
2308      /* 0 -> ??? */
2309      return IMGTOOLERR_CORRUPTIMAGE;
2310   if (AB_address == 1)
2311      /* EOF */
2312      return IMGTOOLERR_UNEXPECTED;
2313   AB_address -= 2;
2314   for (i=0; i<AB_num; i++)
2315   {
2316      AB_address = mfs_get_ABlink(fileref->l2_img, AB_address);
2317      if ((AB_address == 0) || (AB_address >= fileref->l2_img->numABs+2))
2318         /* 0 -> empty block: there is no way an empty block could make it
2319         into the link chain!!! */
2320         return IMGTOOLERR_CORRUPTIMAGE;
2321      if (AB_address == 1)
2322         /* EOF */
2323         return IMGTOOLERR_UNEXPECTED;
2324      AB_address -= 2;
2325   }
2326
2327   *block_address = fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB
2328                  + block_num % fileref->l2_img->blocksperAB;
2329
2330   return IMGTOOLERR_SUCCESS;
2331}
2332
2333/*
2334   mfs_file_allocABs
2335
2336   Allocate a chunk of ABs
2337
2338   fileref (I/O): open mac file reference
2339   lastAB (I): AB address on disk of last file AB (only if
2340      fileref->u.mfs.stBlk != 1)
2341   allocABs (I): number of ABs to allocate in addition to the current file
2342      allocation
2343   fblock (I): first file block to allocate (used for tag data)
2344
2345   Return imgtool error code
2346*/
2347static imgtoolerr_t mfs_file_allocABs(mac_fileref *fileref, UINT16 lastAB, UINT32 allocABs, UINT32 fblock)
2348{
2349   int numABs = fileref->l2_img->numABs;
2350   int free_ABs;
2351   int i, j;
2352   floppy_tag_record tag;
2353   int extentBaseAB, extentABlen;
2354   int firstBestExtentBaseAB = 0, firstBestExtentABlen;
2355   int secondBestExtentBaseAB = 0, secondBestExtentABlen;
2356   imgtoolerr_t err;
2357
2358   /* return if done */
2359   if (! allocABs)
2360      return IMGTOOLERR_SUCCESS;
2361
2362   /* compute free space */
2363   free_ABs = 0;
2364   for (i=0; i<numABs; i++)
2365   {
2366      if (mfs_get_ABlink(fileref->l2_img, i) == 0)
2367      {
2368         if (TAG_CHECKS)
2369         {
2370            /* optional check */
2371            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2372            {
2373               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2374               {
2375                  err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + i * fileref->l2_img->blocksperAB + j, &tag);
2376                  if (err)
2377                     return err;
2378
2379                  if (get_UINT32BE(tag.fileID) != 0)
2380                  {
2381                     /*return IMGTOOLERR_CORRUPTIMAGE;*/
2382                     goto corrupt_free_block;
2383                  }
2384               }
2385            }
2386         }
2387
2388         free_ABs++;
2389      }
2390corrupt_free_block:
2391      ;
2392   }
2393
2394   /* check we have enough free space */
2395   if (free_ABs < allocABs)
2396      return IMGTOOLERR_NOSPACE;
2397
2398   if (fileref->u.mfs.stBlk != 1)
2399   {   /* try to extend last file extent */
2400      /* append free ABs after last AB */
2401      for (i=lastAB+1; (mfs_get_ABlink(fileref->l2_img, i) == 0) && (allocABs > 0) && (i < numABs); i++)
2402      {
2403         if (TAG_CHECKS)
2404         {
2405            /* optional check */
2406            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2407            {
2408               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2409               {
2410                  err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + i * fileref->l2_img->blocksperAB + j, &tag);
2411                  if (err)
2412                     return err;
2413
2414                  if (get_UINT32BE(tag.fileID) != 0)
2415                  {
2416                     /*return IMGTOOLERR_CORRUPTIMAGE;*/
2417                     goto corrupt_free_block2;
2418                  }
2419               }
2420            }
2421         }
2422
2423         mfs_set_ABlink(fileref->l2_img, lastAB, i+2);
2424         lastAB = i;
2425         allocABs--;
2426         free_ABs--;
2427      }
2428corrupt_free_block2:
2429      /* return if done */
2430      if (! allocABs)
2431      {
2432         mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2433         fileref->l2_img->freeABs = free_ABs;
2434         return IMGTOOLERR_SUCCESS;   /* done */
2435      }
2436   }
2437
2438   while (allocABs)
2439   {
2440      /* find smallest data block at least nb_alloc_physrecs in length, and largest data block less than nb_alloc_physrecs in length */
2441      firstBestExtentABlen = INT_MAX;
2442      secondBestExtentABlen = 0;
2443      for (i=0; i<numABs; i++)
2444      {
2445         if (mfs_get_ABlink(fileref->l2_img, i) == 0)
2446         {   /* found one free block */
2447            /* compute its length */
2448            extentBaseAB = i;
2449            extentABlen = 0;
2450            while ((i<numABs) && (mfs_get_ABlink(fileref->l2_img, i) == 0))
2451            {
2452               if (TAG_CHECKS)
2453               {
2454                  /* optional check */
2455                  if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2456                  {
2457                     for (j=0; j<fileref->l2_img->blocksperAB; j++)
2458                     {
2459                        err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + i * fileref->l2_img->blocksperAB + j, &tag);
2460                        if (err)
2461                           return err;
2462
2463                        if (get_UINT32BE(tag.fileID) != 0)
2464                        {
2465                           /*return IMGTOOLERR_CORRUPTIMAGE;*/
2466                           goto corrupt_free_block3;
2467                        }
2468                     }
2469                  }
2470               }
2471
2472               extentABlen++;
2473               i++;
2474            }
2475corrupt_free_block3:
2476            /* compare to previous best and second-best blocks */
2477            if ((extentABlen < firstBestExtentABlen) && (extentABlen >= allocABs))
2478            {
2479               firstBestExtentBaseAB = extentBaseAB;
2480               firstBestExtentABlen = extentABlen;
2481               if (extentABlen == allocABs)
2482                  /* no need to search further */
2483                  break;
2484            }
2485            else if ((extentABlen > secondBestExtentABlen) && (extentABlen < allocABs))
2486            {
2487               secondBestExtentBaseAB = extentBaseAB;
2488               secondBestExtentABlen = extentABlen;
2489            }
2490         }
2491      }
2492
2493      if (firstBestExtentABlen != INT_MAX)
2494      {   /* found one contiguous block which can hold it all */
2495         extentABlen = allocABs;
2496         for (i=0; i<allocABs; i++)
2497         {
2498            if (fileref->u.mfs.stBlk != 1)
2499               mfs_set_ABlink(fileref->l2_img, lastAB, firstBestExtentBaseAB+i+2);
2500            else
2501               fileref->u.mfs.stBlk = firstBestExtentBaseAB+i+2;
2502            lastAB = firstBestExtentBaseAB+i;
2503            free_ABs--;
2504            /* set tag to allocated */
2505            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2506            {
2507               set_UINT32BE(&tag.fileID, fileref->fileID);
2508               tag.ftype = 1;
2509               if ((fileref->forkType) == rsrc_fork)
2510                  tag.ftype |= 2;
2511               tag.fattr = /*fattr*/ 0;      /* ***TODO*** */
2512               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2513               {
2514                  set_UINT16BE(&tag.fblock, fblock & 0xffff);
2515                  set_UINT32BE(&tag.wrCnt, mac_time_now());
2516                  err = image_write_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + lastAB * fileref->l2_img->blocksperAB + j, &tag);
2517                  if (err)
2518                  {
2519                     mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2520                     fileref->l2_img->freeABs = free_ABs;
2521                     return err;
2522                  }
2523                  fblock++;
2524               }
2525            }
2526         }
2527         allocABs = 0;
2528         mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2529         fileref->l2_img->freeABs = free_ABs;
2530         /*return IMGTOOLERR_SUCCESS;*/   /* done */
2531      }
2532      else if (secondBestExtentABlen != 0)
2533      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
2534         for (i=0; i<secondBestExtentABlen; i++)
2535         {
2536            if (fileref->u.mfs.stBlk != 1)
2537               mfs_set_ABlink(fileref->l2_img, lastAB, secondBestExtentBaseAB+i+2);
2538            else
2539               fileref->u.mfs.stBlk = secondBestExtentBaseAB+i+2;
2540            lastAB = secondBestExtentBaseAB+i;
2541            free_ABs--;
2542            /* set tag to allocated */
2543            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2544            {
2545               set_UINT32BE(&tag.fileID, fileref->fileID);
2546               tag.ftype = 1;
2547               if ((fileref->forkType) == rsrc_fork)
2548                  tag.ftype |= 2;
2549               tag.fattr = /*fattr*/ 0;      /* ***TODO*** */
2550               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2551               {
2552                  set_UINT16BE(&tag.fblock, fblock & 0xffff);
2553                  set_UINT32BE(&tag.wrCnt, mac_time_now());
2554                  err = image_write_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + lastAB * fileref->l2_img->blocksperAB + j, &tag);
2555                  if (err)
2556                  {
2557                     mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2558                     fileref->l2_img->freeABs = free_ABs;
2559                     return err;
2560                  }
2561                  fblock++;
2562               }
2563            }
2564         }
2565         allocABs -= secondBestExtentABlen;
2566      }
2567      else
2568      {
2569         mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2570         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
2571      }
2572   }
2573
2574   return IMGTOOLERR_SUCCESS;
2575}
2576
2577/*
2578   mfs_file_setABeof
2579
2580   Set physical file EOF in ABs
2581
2582   fileref (I/O): open mac file reference
2583   newABeof (I): desired number of allocated ABs for this file
2584
2585   Return imgtool error code
2586*/
2587static imgtoolerr_t mfs_file_setABeof(mac_fileref *fileref, UINT32 newABeof)
2588{
2589   UINT16 AB_address = 0;
2590   UINT16 AB_link;
2591   int i, j;
2592   floppy_tag_record tag;
2593   int MDB_dirty = 0;
2594   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
2595
2596
2597   assert(fileref->l2_img->format == L2I_MFS);
2598
2599   /* run through link chain until we reach the old or the new EOF */
2600   AB_link = fileref->u.mfs.stBlk;
2601   if ((AB_link == 0) || (AB_link >= fileref->l2_img->numABs+2))
2602      /* 0 -> ??? */
2603      return IMGTOOLERR_CORRUPTIMAGE;
2604   for (i=0; (i<newABeof) && (AB_link!=1); i++)
2605   {
2606      AB_address = AB_link - 2;
2607      AB_link = mfs_get_ABlink(fileref->l2_img, AB_address);
2608      if ((AB_link == 0) || (AB_link >= fileref->l2_img->numABs+2))
2609         /* 0 -> empty block: there is no way an empty block could make it
2610         into the link chain!!! */
2611         return IMGTOOLERR_CORRUPTIMAGE;
2612
2613      if (TAG_CHECKS)
2614      {
2615         /* optional check */
2616         if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2617         {
2618            for (j=0; j<fileref->l2_img->blocksperAB; j++)
2619            {
2620               err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB + j, &tag);
2621               if (err)
2622                  return err;
2623
2624               if ((get_UINT32BE(tag.fileID) != fileref->fileID)
2625                  || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
2626                  || (get_UINT16BE(tag.fblock) != ((i * fileref->l2_img->blocksperAB + j) & 0xffff)))
2627               {
2628                  return IMGTOOLERR_CORRUPTIMAGE;
2629               }
2630            }
2631         }
2632      }
2633   }
2634
2635   if (i == newABeof)
2636   {   /* new EOF is shorter than old one */
2637      /* mark new eof */
2638      if (i==0)
2639         fileref->u.mfs.stBlk = 1;
2640      else
2641      {
2642         mfs_set_ABlink(fileref->l2_img, AB_address, 1);
2643         MDB_dirty = 1;
2644      }
2645
2646      /* free all remaining blocks */
2647      while (AB_link != 1)
2648      {
2649         AB_address = AB_link - 2;
2650         AB_link = mfs_get_ABlink(fileref->l2_img, AB_address);
2651         if ((AB_link == 0) || (AB_link >= fileref->l2_img->numABs+2))
2652         {   /* 0 -> empty block: there is no way an empty block could make
2653            it into the link chain!!! */
2654            if (MDB_dirty)
2655            {   /* update MDB (freeABs field) and ABLink array */
2656               err = mfs_update_mdb(fileref->l2_img);
2657               if (err)
2658                  return err;
2659            }
2660            return IMGTOOLERR_CORRUPTIMAGE;
2661         }
2662
2663         if (TAG_CHECKS)
2664         {
2665            /* optional check */
2666            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2667            {
2668               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2669               {
2670                  err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB + j, &tag);
2671                  if (err)
2672                     return err;
2673
2674                  if ((get_UINT32BE(tag.fileID) != fileref->fileID)
2675                     || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
2676                     || (get_UINT16BE(tag.fblock) != ((i * fileref->l2_img->blocksperAB + j) & 0xffff)))
2677                  {
2678                     return IMGTOOLERR_CORRUPTIMAGE;
2679                  }
2680               }
2681            }
2682         }
2683
2684         mfs_set_ABlink(fileref->l2_img, AB_address, 0);
2685         fileref->l2_img->freeABs++;
2686         MDB_dirty = 1;
2687         /* set tag to free */
2688         if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2689         {
2690            memset(&tag, 0, sizeof(tag));
2691            for (j=0; j<fileref->l2_img->blocksperAB; j++)
2692            {
2693               err = image_write_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB + j, &tag);
2694               if (err)
2695                  return err;
2696            }
2697         }
2698         i++;
2699      }
2700   }
2701   else
2702   {   /* new EOF is larger than old one */
2703      err = mfs_file_allocABs(fileref, AB_address, newABeof - i, i * fileref->l2_img->blocksperAB);
2704      if (err)
2705         return err;
2706      MDB_dirty = 1;
2707   }
2708
2709   if (MDB_dirty)
2710   {   /* update MDB (freeABs field) and ABLink array */
2711      err = mfs_update_mdb(fileref->l2_img);
2712      if (err)
2713         return err;
2714   }
2715
2716   fileref->pLen = newABeof * (fileref->l2_img->blocksperAB * 512);
2717
2718   return IMGTOOLERR_SUCCESS;
2719}
2720
2721#ifdef UNUSED_FUNCTION
2722/*
2723   mfs_hashString
2724
2725   Hash a string: under MFS, this provides the resource ID of the comment
2726   resource associated with the file whose name is provided (FCMT resource
2727   type).
2728
2729   Ripped from Apple technote TB06 (converted from 68k ASM to C)
2730
2731   string (I): string to hash
2732
2733   Returns hash value
2734*/
2735static int mfs_hashString(const mac_str255 string)
2736{
2737   int reply;
2738   int len;
2739   int i;
2740
2741   len = string[0];
2742
2743   reply = 0;
2744   for (i=0; i<len; i++)
2745   {
2746      reply ^= string[i+1];
2747      if (reply & 1)
2748         reply = ((reply >> 1) & 0x7fff) | ~0x7fff;
2749      else
2750         reply = ((reply >> 1) & 0x7fff);
2751      if (! (reply & 0x8000))
2752         reply = - reply;
2753   }
2754
2755   return reply;
2756}
2757#endif
2758
2759#if 0
2760#pragma mark -
2761#pragma mark HFS IMPLEMENTATION
2762#endif
2763
2764/*
2765   HFS extents B-tree key
2766*/
2767typedef struct hfs_extentKey
2768{
2769   UINT8    keyLength;      /* length of key, excluding this field */
2770   UINT8    forkType;      /* 0 = data fork, FF = resource fork */
2771   UINT32BE fileID;      /* file ID */
2772   UINT16BE startBlock;   /* first file allocation block number in this extent */
2773} hfs_extentKey;
2774enum
2775{
2776   keyLength_hfs_extentKey = sizeof(hfs_extentKey) - sizeof(UINT8)
2777};
2778
2779/*
2780   HFS catalog B-tree key
2781*/
2782typedef struct hfs_catKey
2783{
2784   UINT8    keyLen;      /* key length */
2785   UINT8    resrv1;      /* reserved */
2786   UINT32BE parID;         /* parent directory ID */
2787   mac_str31 cName;      /* catalog node name */
2788                     /* note that in index nodes, it is a mac_str31, but
2789                        in leaf keys it's a variable-length string */
2790} hfs_catKey;
2791
2792/*
2793   HFS catalog data record for a folder - 70 bytes
2794*/
2795typedef struct hfs_catFolderData
2796{
2797   UINT16BE recordType;      /* record type */
2798   UINT16BE flags;            /* folder flags */
2799   UINT16BE valence;         /* folder valence */
2800   UINT32BE folderID;         /* folder ID */
2801   UINT32BE createDate;      /* date and time of creation */
2802   UINT32BE modifyDate;      /* date and time of last modification */
2803   UINT32BE backupDate;      /* date and time of last backup */
2804   mac_DInfo userInfo;         /* Finder information */
2805   mac_DXInfo finderInfo;      /* additional Finder information */
2806   UINT32BE reserved[4];      /* reserved - set to zero */
2807} hfs_catFolderData;
2808
2809/*
2810   HFS catalog data record for a file - 102 bytes
2811*/
2812typedef struct hfs_catFileData
2813{
2814   UINT16BE recordType;      /* record type */
2815   UINT8    flags;            /* file flags */
2816   UINT8    fileType;         /* file type (reserved, always 0?) */
2817   mac_FInfo userInfo;         /* Finder information */
2818   UINT32BE fileID;         /* file ID */
2819   UINT16BE dataStartBlock;   /* not used - set to zero */
2820   UINT32BE dataLogicalSize;   /* logical EOF of data fork */
2821   UINT32BE dataPhysicalSize;   /* physical EOF of data fork */
2822   UINT16BE rsrcStartBlock;   /* not used - set to zero */
2823   UINT32BE rsrcLogicalSize;   /* logical EOF of resource fork */
2824   UINT32BE rsrcPhysicalSize;   /* physical EOF of resource fork */
2825   UINT32BE createDate;      /* date and time of creation */
2826   UINT32BE modifyDate;      /* date and time of last modification */
2827   UINT32BE backupDate;      /* date and time of last backup */
2828   mac_FXInfo finderInfo;      /* additional Finder information */
2829   UINT16BE clumpSize;         /* file clump size (not used) */
2830   hfs_extent_3 dataExtents;   /* first data fork extent record */
2831   hfs_extent_3 rsrcExtents;   /* first resource fork extent record */
2832   UINT32BE reserved;         /* reserved - set to zero */
2833} hfs_catFileData;
2834
2835/*
2836   HFS catalog data record for a thread - 46 bytes
2837
2838   The key for a thread record features the CNID of the item and an empty
2839   name, instead of the CNID of the parent and the item name.
2840*/
2841typedef struct hfs_catThreadData
2842{
2843   UINT16BE recordType;      /* record type */
2844   UINT32BE reserved[2];      /* reserved - set to zero */
2845   UINT32BE parID;            /* parent ID for this catalog node */
2846   mac_str31 nodeName;         /* name of this catalog node */
2847} hfs_catThreadData;
2848
2849/*
2850   union for all types at once
2851*/
2852typedef union hfs_catData
2853{
2854   UINT16BE dataType;
2855   hfs_catFolderData folder;
2856   hfs_catFileData file;
2857   hfs_catThreadData thread;
2858} hfs_catData;
2859
2860/*
2861   HFS catalog record types
2862*/
2863enum
2864{
2865   hcrt_Folder         = 0x0100,   /* Folder record */
2866   hcrt_File         = 0x0200,   /* File record */
2867   hcrt_FolderThread   = 0x0300,   /* Folder thread record */
2868   hcrt_FileThread      = 0x0400   /* File thread record */
2869};
2870
2871/*
2872   Catalog file record flags
2873
2874   This is similar to the MFS catalog flag field, but the "thread exists" flag
2875   (0x02) is specific to HFS/HFS+, whereas the "Record in use" flag (0x80) is
2876   only used by MFS.
2877*/
2878enum
2879{
2880   cfrf_fileLocked      = 0x01,      /* file is locked and cannot be written to */
2881   cfrf_threadExists   = 0x02      /* a file thread record exists for this file */
2882};
2883
2884/*
2885   BT functions used by HFS functions
2886*/
2887typedef struct BT_leaf_rec_enumerator
2888{
2889   mac_BTref *BTref;
2890   UINT32 cur_node;
2891   int cur_rec;
2892} BT_leaf_rec_enumerator;
2893
2894static imgtoolerr_t BT_open(mac_BTref *BTref, int (*key_compare_func)(const void *key1, const void *key2), int is_extent);
2895static void BT_close(mac_BTref *BTref);
2896static imgtoolerr_t BT_search_leaf_rec(mac_BTref *BTref, const void *search_key,
2897                        UINT32 *node_ID, int *record_ID,
2898                        void **record_ptr, int *record_len,
2899                        int search_exact_match, int *match_found);
2900static imgtoolerr_t BT_get_keyed_record_data(mac_BTref *BTref, void *rec_ptr, int rec_len, void **data_ptr, int *data_len);
2901static imgtoolerr_t BT_leaf_rec_enumerator_open(mac_BTref *BTref, BT_leaf_rec_enumerator *enumerator);
2902static imgtoolerr_t BT_leaf_rec_enumerator_read(BT_leaf_rec_enumerator *enumerator, void **record_ptr, int *rec_len);
2903
2904typedef struct hfs_cat_enumerator
2905{
2906   mac_l2_imgref *l2_img;
2907   BT_leaf_rec_enumerator BT_enumerator;
2908   UINT32 parID;
2909} hfs_cat_enumerator;
2910
2911/*
2912   hfs_open_extents_file
2913
2914   Open the file extents B-tree file
2915
2916   l2_img (I/O): level-2 image reference
2917   mdb (I): copy of the MDB block
2918   fileref (O): mac open file reference
2919
2920   Return imgtool error code
2921*/
2922static imgtoolerr_t hfs_open_extents_file(mac_l2_imgref *l2_img, const hfs_mdb *mdb, mac_fileref *fileref)
2923{
2924   assert(l2_img->format == L2I_HFS);
2925
2926   fileref->l2_img = l2_img;
2927
2928   fileref->fileID = 3;
2929   fileref->forkType = 0x00;
2930
2931   fileref->eof = fileref->pLen = get_UINT32BE(mdb->xtFlSize);
2932   memcpy(fileref->u.hfs.extents, mdb->xtExtRec, sizeof(hfs_extent_3));
2933
2934   fileref->crPs = 0;
2935
2936   fileref->reload_buf = TRUE;
2937
2938   return IMGTOOLERR_SUCCESS;
2939}
2940
2941/*
2942   hfs_open_cat_file
2943
2944   Open the disk catalog B-tree file
2945
2946   l2_img (I/O): level-2 image reference
2947   mdb (I): copy of the MDB block
2948   fileref (O): mac open file reference
2949
2950   Return imgtool error code
2951*/
2952static imgtoolerr_t hfs_open_cat_file(mac_l2_imgref *l2_img, const hfs_mdb *mdb, mac_fileref *fileref)
2953{
2954   assert(l2_img->format == L2I_HFS);
2955
2956   fileref->l2_img = l2_img;
2957
2958   fileref->fileID = 4;
2959   fileref->forkType = 0x00;
2960
2961   fileref->eof = fileref->pLen = get_UINT32BE(mdb->ctFlSize);
2962   memcpy(fileref->u.hfs.extents, mdb->ctExtRec, sizeof(hfs_extent_3));
2963
2964   fileref->crPs = 0;
2965
2966   fileref->reload_buf = TRUE;
2967
2968   return IMGTOOLERR_SUCCESS;
2969}
2970
2971/*
2972   hfs_extentKey_compare
2973
2974   key compare function for file extents B-tree
2975
2976   p1 (I): pointer to first key
2977   p2 (I): pointer to second key
2978
2979   Return a zero the two keys are equal, a negative value if the key pointed
2980   to by p1 is less than the key pointed to by p2, and a positive value if the
2981   key pointed to by p1 is greater than the key pointed to by p2.
2982*/
2983static int hfs_extentKey_compare(const void *p1, const void *p2)
2984{
2985   const hfs_extentKey *key1 = p1;
2986   const hfs_extentKey *key2 = p2;
2987
2988   /* let's keep it simple for now */
2989   return memcmp(key1, key2, sizeof(hfs_extentKey));
2990}
2991
2992/*
2993   hfs_catKey_compare
2994
2995   key compare function for disk catalog B-tree
2996
2997   p1 (I): pointer to first key
2998   p2 (I): pointer to second key
2999
3000   Return a zero the two keys are equal, a negative value if the key pointed
3001   to by p1 is less than the key pointed to by p2, and a positive value if the
3002   key pointed to by p1 is greater than the key pointed to by p2.
3003*/
3004static int hfs_catKey_compare(const void *p1, const void *p2)
3005{
3006   const hfs_catKey *key1 = p1;
3007   const hfs_catKey *key2 = p2;
3008
3009   if (get_UINT32BE(key1->parID) != get_UINT32BE(key2->parID))
3010      return (get_UINT32BE(key1->parID) < get_UINT32BE(key2->parID)) ? -1 : +1;
3011
3012   return mac_stricmp(key1->cName, key2->cName);
3013}
3014
3015/*
3016   hfs_image_open
3017
3018   Open a HFS image.  Image must already be open on level 1.
3019
3020   l2_img (I/O): level-2 image reference to open (l1_img and format fields
3021      must be initialized)
3022   img_open_buf (I): buffer with the MDB block
3023
3024   Return imgtool error code
3025*/
3026static imgtoolerr_t hfs_image_open(imgtool_image *image, imgtool_stream *stream)
3027{
3028   imgtoolerr_t err;
3029   mac_l2_imgref *l2_img;
3030   img_open_buf buf_local;
3031   img_open_buf *buf;
3032
3033   l2_img = get_imgref(image);
3034   l2_img->l1_img.image = image;
3035   l2_img->l1_img.heads = 2;
3036   l2_img->format = L2I_HFS;
3037
3038   /* read MDB */
3039   err = image_read_block(&l2_img->l1_img, 2, &buf_local.raw);
3040   if (err)
3041      return err;
3042   buf = &buf_local;
3043
3044   /* check signature word */
3045   if ((buf->hfs_mdb.sigWord[0] != 0x42) || (buf->hfs_mdb.sigWord[1] != 0x44)
3046         || (buf->hfs_mdb.VN[0] > 27))
3047      return IMGTOOLERR_CORRUPTIMAGE;
3048
3049   l2_img->u.hfs.VBM_start = get_UINT16BE(buf->hfs_mdb.VBMSt);
3050
3051   l2_img->numABs = get_UINT16BE(buf->hfs_mdb.nmAlBlks);
3052   if (get_UINT32BE(buf->hfs_mdb.alBlkSiz) % 512)
3053      return IMGTOOLERR_CORRUPTIMAGE;
3054   l2_img->blocksperAB = get_UINT32BE(buf->hfs_mdb.alBlkSiz) / 512;
3055   l2_img->u.hfs.ABStart = get_UINT16BE(buf->hfs_mdb.alBlSt);
3056
3057   l2_img->nxtCNID = get_UINT32BE(buf->hfs_mdb.nxtCNID);
3058
3059   l2_img->freeABs = get_UINT16BE(buf->hfs_mdb.freeABs);
3060
3061   mac_strcpy(l2_img->u.hfs.volname, buf->hfs_mdb.VN);
3062
3063   /* open extents and catalog BT */
3064   err = hfs_open_extents_file(l2_img, &buf->hfs_mdb, &l2_img->u.hfs.extents_BT.fileref);
3065   if (err)
3066      return err;
3067   err = BT_open(&l2_img->u.hfs.extents_BT, hfs_extentKey_compare, TRUE);
3068   if (err)
3069      return err;
3070   if ((l2_img->u.hfs.extents_BT.attributes & btha_bigKeysMask)
3071         /*|| (l2_img->u.hfs.extents_BT.attributes & kBTVariableIndexKeysMask)*/
3072         || (l2_img->u.hfs.extents_BT.maxKeyLength != 7))
3073   {   /* This is not supported by the HFS format */
3074      /* Variable Index keys are not supported either, but hopefully it will
3075      not break this imgtool module if it set (though it would probably break
3076      a real macintosh) */
3077      BT_close(&l2_img->u.hfs.extents_BT);
3078      return IMGTOOLERR_CORRUPTIMAGE;
3079   }
3080   err = hfs_open_cat_file(l2_img, &buf->hfs_mdb, &l2_img->u.hfs.cat_BT.fileref);
3081   if (err)
3082   {
3083      BT_close(&l2_img->u.hfs.extents_BT);
3084      return err;
3085   }
3086   err = BT_open(&l2_img->u.hfs.cat_BT, hfs_catKey_compare, FALSE);
3087   if (err)
3088   {
3089      return err;
3090   }
3091   if ((l2_img->u.hfs.cat_BT.attributes & btha_bigKeysMask)
3092         /*|| (l2_img->u.hfs.cat_BT.attributes & kBTVariableIndexKeysMask)*/
3093         || (l2_img->u.hfs.cat_BT.maxKeyLength != 37))
3094   {   /* This is not supported by the HFS format */
3095      /* Variable Index keys are not supported either, but hopefully it will
3096      not break this imgtool module if it set (though it would probably break
3097      a real macintosh) */
3098      BT_close(&l2_img->u.hfs.extents_BT);
3099      BT_close(&l2_img->u.hfs.cat_BT);
3100      return IMGTOOLERR_CORRUPTIMAGE;
3101   }
3102
3103   /* extract volume bitmap */
3104   {
3105      int byte_len = (l2_img->numABs + 7) / 8;
3106      int cur_byte = 0;
3107      int cur_block = l2_img->u.hfs.VBM_start;
3108
3109      while (cur_byte < byte_len)
3110      {
3111         /* read next block */
3112         err = image_read_block(&l2_img->l1_img, cur_block, buf->raw);
3113         if (err)
3114            return err;
3115         cur_block++;
3116
3117         /* append this block to VBM */
3118         memcpy(l2_img->u.hfs.VBM+cur_byte, buf->raw, 512);
3119         cur_byte += 512;
3120      }
3121   }
3122
3123   return IMGTOOLERR_SUCCESS;
3124}
3125
3126#ifdef UNUSED_FUNCTION
3127/*
3128   hfs_image_close
3129
3130   Close a HFS image.
3131
3132   l2_img (I/O): level-2 image reference
3133*/
3134static void hfs_image_close(mac_l2_imgref *l2_img)
3135{
3136   assert(l2_img->format == L2I_HFS);
3137
3138   BT_close(&l2_img->u.hfs.extents_BT);
3139   BT_close(&l2_img->u.hfs.cat_BT);
3140}
3141#endif
3142
3143/*
3144   hfs_get_cat_record_data
3145
3146   extract data from a catalog B-tree leaf record
3147
3148   l2_img (I/O): level-2 image reference
3149   rec_raw (I): pointer to record key and data, as returned by
3150      BT_node_get_keyed_record
3151   rec_len (I): total length of record, as returned by
3152      BT_node_get_keyed_record
3153   rec_key (O): set to point to record key
3154   rec_data (O): set to point to record data
3155
3156   Return imgtool error code
3157*/
3158static imgtoolerr_t hfs_get_cat_record_data(mac_l2_imgref *l2_img, void *rec_raw, int rec_len, hfs_catKey **rec_key, hfs_catData **rec_data)
3159{
3160   hfs_catKey *lrec_key;
3161   void *rec_data_raw;
3162   hfs_catData *lrec_data;
3163   int rec_data_len;
3164   int min_data_size;
3165   imgtoolerr_t err;
3166
3167
3168   assert(l2_img->format == L2I_HFS);
3169
3170   lrec_key = rec_raw;
3171   /* check that key is long enough to hold it all */
3172   if ((lrec_key->keyLen+1) < (offsetof(hfs_catKey, cName) + lrec_key->cName[0] + 1))
3173      return IMGTOOLERR_CORRUPTIMAGE;
3174
3175   /* get pointer to record data */
3176   err = BT_get_keyed_record_data(&l2_img->u.hfs.cat_BT, rec_raw, rec_len, &rec_data_raw, &rec_data_len);
3177   if (err)
3178      return err;
3179   lrec_data = rec_data_raw;
3180
3181   /* extract record type */
3182   if (rec_data_len < 2)
3183      return IMGTOOLERR_CORRUPTIMAGE;
3184
3185   /* check that the record is large enough for its type */
3186   switch (get_UINT16BE(lrec_data->dataType))
3187   {
3188   case hcrt_Folder:
3189      min_data_size = sizeof(hfs_catFolderData);
3190      break;
3191
3192   case hcrt_File:
3193      min_data_size = sizeof(hfs_catFileData);
3194      break;
3195
3196   case hcrt_FolderThread:
3197   case hcrt_FileThread:
3198      min_data_size = sizeof(hfs_catThreadData);
3199      break;
3200
3201   default:
3202      /* records of unknown type can be safely ignored */
3203      min_data_size = 0;
3204      break;
3205   }
3206
3207   if (rec_data_len < min_data_size)
3208      return IMGTOOLERR_CORRUPTIMAGE;
3209
3210   if (rec_key)
3211      *rec_key = lrec_key;
3212   if (rec_data)
3213      *rec_data = lrec_data;
3214
3215   return IMGTOOLERR_SUCCESS;
3216}
3217
3218/*
3219   hfs_cat_open
3220
3221   Open an enumerator on the disk catalog
3222
3223   l2_img (I/O): level-2 image reference
3224   enumerator (O): open catalog enumerator reference
3225
3226   Return imgtool error code
3227*/
3228static imgtoolerr_t hfs_cat_open(mac_l2_imgref *l2_img, const char *path, hfs_cat_enumerator *enumerator)
3229{
3230   imgtoolerr_t err;
3231   UINT32 parID;
3232   mac_str255 filename;
3233   mac_dirent cat_info;
3234
3235   assert(l2_img->format == L2I_HFS);
3236
3237   /* resolve path and fetch file info from directory/catalog */
3238   err = mac_lookup_path(l2_img, path, &parID, filename, &cat_info, FALSE);
3239   if (err)
3240      return err;
3241   if (cat_info.dataRecType != hcrt_Folder)
3242      return IMGTOOLERR_FILENOTFOUND;
3243
3244   enumerator->l2_img = l2_img;
3245   enumerator->parID = parID;
3246
3247   return BT_leaf_rec_enumerator_open(&l2_img->u.hfs.cat_BT, &enumerator->BT_enumerator);
3248}
3249
3250/*
3251   hfs_cat_read
3252
3253   Enumerate the disk catalog
3254
3255   enumerator (I/O): open catalog enumerator reference
3256   rec_key (O): set to point to record key
3257   rec_data (O): set to point to record data
3258
3259   Return imgtool error code
3260*/
3261static imgtoolerr_t hfs_cat_read(hfs_cat_enumerator *enumerator, hfs_catKey **rec_key, hfs_catData **rec_data)
3262{
3263   void *rec;
3264   int rec_len;
3265   imgtoolerr_t err;
3266
3267
3268   *rec_key = NULL;
3269   *rec_data = NULL;
3270
3271   /* read next record */
3272   err = BT_leaf_rec_enumerator_read(&enumerator->BT_enumerator, &rec, &rec_len);
3273   if (err)
3274      return err;
3275
3276   /* check EOList condition */
3277   if (rec == NULL)
3278      return IMGTOOLERR_SUCCESS;
3279
3280   /* extract record data */
3281   err = hfs_get_cat_record_data(enumerator->l2_img, rec, rec_len, rec_key, rec_data);
3282   if (err)
3283      return err;
3284
3285   return IMGTOOLERR_SUCCESS;
3286}
3287
3288/*
3289   hfs_cat_search
3290
3291   Search the catalog for a given file
3292
3293   l2_img (I/O): level-2 image reference
3294   parID (I): CNID of file parent directory
3295   cName (I): file name
3296   rec_key (O): set to point to record key
3297   rec_data (O): set to point to record data
3298
3299   Return imgtool error code
3300*/
3301static imgtoolerr_t hfs_cat_search(mac_l2_imgref *l2_img, UINT32 parID, const mac_str31 cName, hfs_catKey **rec_key, hfs_catData **rec_data)
3302{
3303   hfs_catKey search_key;
3304   void *rec;
3305   int rec_len;
3306   imgtoolerr_t err;
3307
3308   assert(l2_img->format == L2I_HFS);
3309
3310   if (cName[0] > 31)
3311      return IMGTOOLERR_UNEXPECTED;
3312
3313   /* generate search key */
3314   search_key.keyLen = search_key.resrv1 = 0;   /* these fields do not matter
3315                                    to the compare function, so we
3316                                    don't fill them */
3317   set_UINT32BE(&search_key.parID, parID);
3318   mac_strcpy(search_key.cName, cName);
3319
3320   /* search key */
3321   err = BT_search_leaf_rec(&l2_img->u.hfs.cat_BT, &search_key, NULL, NULL, &rec, &rec_len, TRUE, NULL);
3322   if (err)
3323      return err;
3324
3325   /* extract record data */
3326   err = hfs_get_cat_record_data(l2_img, rec, rec_len, rec_key, rec_data);
3327   if (err)
3328      return err;
3329
3330   return IMGTOOLERR_SUCCESS;
3331}
3332
3333/*
3334   hfs_lookup_path
3335
3336   Resolve a file path
3337
3338   l2_img (I/O): level-2 image reference
3339   fpath (I): file path (C string)
3340   parID (O): set to the CNID of the file parent directory
3341   filename (O): set to the actual name of the file, with capitalization matching
3342      the one on the volume rather than the one in the fpath parameter (Mac
3343      string)
3344   cat_info (O): catalog info for this file extracted from the catalog file
3345      (may be NULL)
3346
3347   Return imgtool error code
3348*/
3349static imgtoolerr_t hfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, UINT32 *parID, mac_str255 filename, mac_dirent *cat_info)
3350{
3351   const char *element_start;
3352   int element_len;
3353   mac_str255 mac_element_name;
3354   int level;
3355   imgtoolerr_t err;
3356   hfs_catKey *catrec_key = NULL;
3357   hfs_catData *catrec_data = NULL;
3358   UINT16 dataRecType = hcrt_Folder;
3359
3360   /* iterate each path element */
3361   element_start = fpath;
3362   level = 0;
3363   *parID = 2;   /* root parID is 2 */
3364
3365   while(*element_start)
3366   {
3367      /* find next path element */
3368      element_len = strlen(element_start);
3369      /* decode path element name */
3370      c_to_mac_strncpy(mac_element_name, element_start, element_len);
3371
3372      err = hfs_cat_search(l2_img, *parID, mac_element_name, &catrec_key, &catrec_data);
3373      if (err)
3374         return err;
3375
3376      dataRecType = get_UINT16BE(catrec_data->dataType);
3377
3378      /* regular folder/file name */
3379      if (dataRecType == hcrt_Folder)
3380         *parID = get_UINT32BE(catrec_data->folder.folderID);
3381      else if (element_start[element_len + 1])
3382         return IMGTOOLERR_BADFILENAME;
3383
3384      /* iterate */
3385      element_start += element_len + 1;
3386   }
3387
3388   if (catrec_key && (dataRecType == hcrt_File))
3389   {
3390      /* save ref */
3391      *parID = get_UINT32BE(catrec_key->parID);
3392      mac_strcpy(filename, catrec_key->cName);
3393   }
3394
3395   if (cat_info)
3396   {
3397      if (catrec_data && (dataRecType == hcrt_File))
3398      {
3399         cat_info->flFinderInfo = catrec_data->file.userInfo;
3400         cat_info->flXFinderInfo = catrec_data->file.finderInfo;
3401         cat_info->flags = catrec_data->file.flags;
3402         cat_info->fileID = get_UINT32BE(catrec_data->file.fileID);
3403         cat_info->dataLogicalSize = get_UINT32BE(catrec_data->file.dataLogicalSize);
3404         cat_info->dataPhysicalSize = get_UINT32BE(catrec_data->file.dataPhysicalSize);
3405         cat_info->rsrcLogicalSize = get_UINT32BE(catrec_data->file.rsrcLogicalSize);
3406         cat_info->rsrcPhysicalSize = get_UINT32BE(catrec_data->file.rsrcPhysicalSize);
3407         cat_info->createDate = get_UINT32BE(catrec_data->file.createDate);
3408         cat_info->modifyDate = get_UINT32BE(catrec_data->file.modifyDate);
3409      }
3410      else
3411      {
3412         memset(cat_info, 0, sizeof(*cat_info));
3413      }
3414      cat_info->dataRecType = dataRecType;
3415   }
3416
3417   return IMGTOOLERR_SUCCESS;
3418}
3419
3420/*
3421   hfs_file_open_internal
3422
3423   Open a file fork, given its catalog entry.  This function should not be
3424   called directly: call hfs_file_open instead.
3425
3426   l2_img (I/O): level-2 image reference
3427   file_rec (I): catalog entry for the file to open
3428   mac_forkID (I): tells which fork should be opened
3429   fileref (O): mac file reference to open
3430
3431   Return imgtool error code
3432*/
3433static imgtoolerr_t hfs_file_open_internal(mac_l2_imgref *l2_img, const hfs_catFileData *file_rec, mac_forkID fork, mac_fileref *fileref)
3434{
3435   assert(l2_img->format == L2I_HFS);
3436
3437   fileref->l2_img = l2_img;
3438
3439   fileref->fileID = get_UINT32BE(file_rec->fileID);
3440   fileref->forkType = fork;
3441
3442   switch (fork)
3443   {
3444   case data_fork:
3445      fileref->eof = get_UINT32BE(file_rec->dataLogicalSize);
3446      fileref->pLen = get_UINT32BE(file_rec->dataPhysicalSize);
3447      memcpy(fileref->u.hfs.extents, file_rec->dataExtents, sizeof(hfs_extent_3));
3448      break;
3449
3450   case rsrc_fork:
3451      fileref->eof = get_UINT32BE(file_rec->rsrcLogicalSize);
3452      fileref->pLen = get_UINT32BE(file_rec->rsrcPhysicalSize);
3453      memcpy(fileref->u.hfs.extents, file_rec->rsrcExtents, sizeof(hfs_extent_3));
3454      break;
3455   }
3456
3457   fileref->crPs = 0;
3458
3459   fileref->reload_buf = TRUE;
3460
3461   return IMGTOOLERR_SUCCESS;
3462}
3463
3464/*
3465   hfs_file_open
3466
3467   Open a file located on a HFS volume.  This function should not be called
3468   directly: call mac_file_open instead.
3469
3470   l2_img (I/O): level-2 image reference
3471   parID (I): CNID of file parent directory
3472   filename (I): name of the file (Mac string)
3473   mac_forkID (I): tells which fork should be opened
3474   fileref (O): mac file reference to open
3475
3476   Return imgtool error code
3477*/
3478static imgtoolerr_t hfs_file_open(mac_l2_imgref *l2_img, UINT32 parID, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref)
3479{
3480   hfs_catKey *catrec_key;
3481   hfs_catData *catrec_data;
3482   UINT16 dataRecType;
3483   imgtoolerr_t err;
3484
3485   /* lookup file in catalog */
3486   err = hfs_cat_search(l2_img, parID, filename, &catrec_key, &catrec_data);
3487   if (err)
3488      return err;
3489
3490   dataRecType = get_UINT16BE(catrec_data->dataType);
3491
3492   /* file expected */
3493   if (dataRecType != hcrt_File)
3494      return IMGTOOLERR_BADFILENAME;
3495
3496   fileref->u.hfs.parID = get_UINT32BE(catrec_key->parID);
3497   mac_strcpy(fileref->u.hfs.filename, catrec_key->cName);
3498
3499   /* open it */
3500   return hfs_file_open_internal(l2_img, &catrec_data->file, fork, fileref);
3501}
3502
3503/*
3504   hfs_file_get_nth_block_address
3505
3506   Get the disk block address of a given block in an open file on a MFS image.
3507   Called by macintosh file code.
3508
3509   fileref (I/O): open mac file reference
3510   block_num (I): file block index
3511   block_address (O): disk block address for the file block
3512
3513   Return imgtool error code
3514*/
3515static imgtoolerr_t hfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address)
3516{
3517   UINT32 AB_num;
3518   UINT32 cur_AB;
3519   UINT32 i;
3520   void *cur_extents_raw;
3521   hfs_extent *cur_extents;
3522   int cur_extents_len;
3523   void *extents_BT_rec;
3524   int extents_BT_rec_len;
3525   imgtoolerr_t err;
3526   UINT16 AB_address;
3527
3528   assert(fileref->l2_img->format == L2I_HFS);
3529
3530   AB_num = block_num / fileref->l2_img->blocksperAB;
3531   cur_AB = 0;
3532   cur_extents = fileref->u.hfs.extents;
3533
3534   /* first look in catalog tree extents */
3535   for (i=0; i<3; i++)
3536   {
3537      if (AB_num < cur_AB+get_UINT16BE(cur_extents[i].numABlks))
3538         break;
3539      cur_AB += get_UINT16BE(cur_extents[i].numABlks);
3540   }
3541   if (i == 3)
3542   {
3543      /* extent not found: read extents record from extents BT */
3544      hfs_extentKey search_key;
3545      hfs_extentKey *found_key;
3546
3547      search_key.keyLength = keyLength_hfs_extentKey;
3548      search_key.forkType = fileref->forkType;
3549      set_UINT32BE(&search_key.fileID, fileref->fileID);
3550      set_UINT16BE(&search_key.startBlock, AB_num);
3551
3552      /* search for the record with the largest key lower than or equal to
3553      search_key.  The keys are constructed in such a way that, if a record
3554      includes AB_num, it is that one. */
3555      err = BT_search_leaf_rec(&fileref->l2_img->u.hfs.extents_BT, &search_key,
3556                              NULL, NULL, &extents_BT_rec, &extents_BT_rec_len,
3557                              FALSE, NULL);
3558      if (err)
3559         return err;
3560
3561      if (extents_BT_rec == NULL)
3562         return IMGTOOLERR_CORRUPTIMAGE;
3563
3564      found_key = extents_BT_rec;
3565      /* check that this record concerns the correct file */
3566      if ((found_key->forkType != fileref->forkType)
3567         || (get_UINT32BE(found_key->fileID) != fileref->fileID))
3568         return IMGTOOLERR_CORRUPTIMAGE;
3569
3570      /* extract start AB */
3571      cur_AB = get_UINT16BE(found_key->startBlock);
3572      /* get extents pointer */
3573      err = BT_get_keyed_record_data(&fileref->l2_img->u.hfs.extents_BT, extents_BT_rec, extents_BT_rec_len, &cur_extents_raw, &cur_extents_len);
3574      if (err)
3575         return err;
3576      if (cur_extents_len < 3*sizeof(hfs_extent))
3577         return IMGTOOLERR_CORRUPTIMAGE;
3578      cur_extents = cur_extents_raw;
3579
3580      /* pick correct extent in record */
3581      for (i=0; i<3; i++)
3582      {
3583         if (AB_num < cur_AB+get_UINT16BE(cur_extents[i].numABlks))
3584            break;
3585         cur_AB += get_UINT16BE(cur_extents[i].numABlks);
3586      }
3587      if (i == 3)
3588         /* extent not found */
3589         return IMGTOOLERR_CORRUPTIMAGE;
3590   }
3591
3592   AB_address = get_UINT16BE(cur_extents[i].stABN) + (AB_num-cur_AB);
3593
3594   if (AB_address >= fileref->l2_img->numABs)
3595      return IMGTOOLERR_CORRUPTIMAGE;
3596
3597   *block_address = fileref->l2_img->u.hfs.ABStart + AB_address * fileref->l2_img->blocksperAB
3598                  + block_num % fileref->l2_img->blocksperAB;
3599
3600   return IMGTOOLERR_SUCCESS;
3601}
3602
3603#if 0
3604#pragma mark -
3605#pragma mark B-TREE IMPLEMENTATION
3606#endif
3607
3608/*
3609   B-tree (Balanced search tree) files are used by the HFS and HFS+ file
3610   systems: the Extents and Catalog files are both B-Tree.
3611
3612   Note that these B-trees are B+-trees: data is only on the leaf level, and
3613   nodes located on the same level are also linked sequentially, which allows
3614   fast sequenctial access to the catalog file.
3615
3616   These files are normal files, except for the fact that they are not
3617   referenced from the catalog but the MDB.  They are allocated in fixed-size
3618   records of 512 bytes (HFS).  (HFS+ supports any power of two from 512
3619   through 32768, and uses a default of 1024 for Extents, and 4096 for both
3620   Catalog and Attributes.)
3621
3622   Nodes can contain any number of records.  The nodes can be of any of four
3623   types: header node (unique node with b-tree information, pointer to root
3624   node and start of the node allocation bitmap), map nodes (which are created
3625   when the node allocation bitmap outgrows the header node), index nodes
3626   (root and branch node that enable to efficiently search the leaf nodes for
3627   a specific key value), and leaf nodes (which hold the actual user data
3628   records with keys and data).  The first node is always a header node.
3629   Other nodes can be of any of the 3 other type, or they can be free.
3630*/
3631
3632/*
3633   BTNodeHeader
3634
3635   Header of a node record
3636*/
3637typedef struct BTNodeHeader
3638{
3639   UINT32BE fLink;         /* (index of) next node at this level */
3640   UINT32BE bLink;         /* (index of) previous node at this level */
3641   UINT8    kind;         /* kind of node (leaf, index, header, map) */
3642   UINT8    height;      /* zero for header, map; 1 for leaf, 2 through
3643                        treeDepth for index (child is one LESS than
3644                        parent, whatever IM says) */
3645   UINT16BE numRecords;   /* number of records in this node */
3646   UINT16BE reserved;      /* reserved; set to zero */
3647} BTNodeHeader;
3648
3649/*
3650   Constants for BTNodeHeader kind field
3651*/
3652enum
3653{
3654   btnk_leafNode   = 0xff,   /* leaf nodes hold the actual user data records
3655                        with keys and data */
3656   btnk_indexNode   = 0,   /* root and branch node that enable to efficiently
3657                        search the leaf nodes for a specific key value */
3658   btnk_headerNode   = 1,   /* unique node with b-tree information, pointer to
3659                        root node and start of the node allocation
3660                        bitmap */
3661   btnk_mapNode   = 2      /* map nodes are created when the node allocation
3662                        bitmap outgrows the header node */
3663};
3664
3665/*
3666   BTHeaderRecord: first record of a B-tree header node (second record is
3667   unused, and third is node allocation bitmap).
3668*/
3669typedef struct BTHeaderRecord
3670{
3671   UINT16BE treeDepth;      /* maximum height (usually leaf nodes) */
3672   UINT32BE rootNode;      /* node number of root node */
3673   UINT32BE leafRecords;   /* number of leaf records in all leaf nodes */
3674   UINT32BE firstLeafNode;   /* node number of first leaf node */
3675   UINT32BE lastLeafNode;   /* node number of last leaf node */
3676   UINT16BE nodeSize;      /* size of a node, in bytes */
3677   UINT16BE maxKeyLength;   /* maximum length of data (index + leaf) record keys;
3678                        length of all index record keys if
3679                        btha_variableIndexKeysMask attribute flag is not set */
3680   UINT32BE totalNodes;   /* total number of nodes in tree */
3681   UINT32BE freeNodes;      /* number of unused (free) nodes in tree */
3682
3683   UINT16BE reserved1;      /* unused */
3684   UINT32BE clumpSize;      /* used in some HFS implementations? (reserved in
3685                        early HFS implementations, and in HFS Plus) */
3686   UINT8    btreeType;      /* reserved - set to 0 */
3687   UINT8    reserved2;      /* reserved */
3688   UINT32BE attributes;   /* persistent attributes about the tree */
3689   UINT32BE reserved3[16];   /* reserved */
3690} BTHeaderRecord;
3691
3692static imgtoolerr_t BT_check(mac_BTref *BTref, int is_extent);
3693
3694/*
3695   BT_open
3696
3697   Open a file as a B-tree.  The file must be already open as a macintosh
3698   file.
3699
3700   BTref (I/O): B-tree file handle to open (BTref->fileref must have been
3701      open previously)
3702   key_compare_func (I): function that compares two keys
3703   is_extent (I): TRUE if we are opening the extent B-tree (we want to do
3704      extra checks in this case because the extent B-Tree may include extent
3705      records for the extent B-tree itself, and if an extent record for the
3706      extent B-tree is located in an extent that has not been defined by
3707      previous extent records, then we can never retreive this extent record)
3708
3709   Return imgtool error code
3710*/
3711static imgtoolerr_t BT_open(mac_BTref *BTref, int (*key_compare_func)(const void *key1, const void *key2), int is_extent)
3712{
3713   imgtoolerr_t err;
3714   BTNodeHeader node_header;
3715   BTHeaderRecord header_rec;
3716
3717   /* seek to node 0 */
3718   err = mac_file_seek(&BTref->fileref, 0);
3719   if (err)
3720      return err;
3721
3722   /* read node header */
3723   err = mac_file_read(&BTref->fileref, sizeof(node_header), &node_header);
3724   if (err)
3725      return err;
3726
3727   if ((node_header.kind != btnk_headerNode) || (get_UINT16BE(node_header.numRecords) < 3)
3728         || (node_header.height != 0))
3729      return IMGTOOLERR_CORRUPTIMAGE;   /* right??? */
3730
3731   /* CHEESY HACK: we assume that the header record immediately follows the
3732   node header.  This is because we need to know the node length to know where
3733   the record pointers are located, but we need to read the header record to
3734   know the node length. */
3735   err = mac_file_read(&BTref->fileref, sizeof(header_rec), &header_rec);
3736   if (err)
3737      return err;
3738
3739   BTref->nodeSize = get_UINT16BE(header_rec.nodeSize);
3740   BTref->rootNode = get_UINT32BE(header_rec.rootNode);
3741   BTref->firstLeafNode = get_UINT32BE(header_rec.firstLeafNode);
3742   BTref->attributes = get_UINT32BE(header_rec.attributes);
3743   BTref->treeDepth = get_UINT16BE(header_rec.treeDepth);
3744   BTref->maxKeyLength = get_UINT16BE(header_rec.maxKeyLength);
3745
3746   BTref->key_compare_func = key_compare_func;
3747
3748   BTref->node_buf = malloc(BTref->nodeSize);
3749   if (!BTref->node_buf)
3750      return IMGTOOLERR_OUTOFMEMORY;
3751
3752   if (BTREE_CHECKS)
3753   {
3754      /* optional: check integrity of B-tree */
3755      err = BT_check(BTref, is_extent);
3756      if (err)
3757         return err;
3758   }
3759
3760   return IMGTOOLERR_SUCCESS;
3761}
3762
3763/*
3764   BT_close
3765
3766   Close a B-tree
3767
3768   BTref (I/O): open B-tree file handle
3769*/
3770static void BT_close(mac_BTref *BTref)
3771{
3772   free(BTref->node_buf);
3773}
3774
3775/*
3776   BT_read_node
3777
3778   Read a node from a B-tree
3779
3780   BTref (I/O): open B-tree file handle
3781   node_ID (I): index of the node to read
3782   expected_kind (I): kind of the node to read
3783   expected_depth (I): depth of the node to read
3784   dest (O): destination buffer
3785
3786   Return imgtool error code
3787*/
3788static imgtoolerr_t BT_read_node(mac_BTref *BTref, UINT32 node_ID, int expected_kind, int expected_depth, void *dest)
3789{
3790   imgtoolerr_t err;
3791
3792   /* seek to node */
3793   err = mac_file_seek(&BTref->fileref, node_ID*BTref->nodeSize);
3794   if (err)
3795      return err;
3796
3797   /* read it */
3798   err = mac_file_read(&BTref->fileref, BTref->nodeSize, dest);
3799   if (err)
3800      return err;
3801
3802   /* check node kind and depth */
3803   if ((((BTNodeHeader *) dest)->kind != expected_kind)
3804         || (((BTNodeHeader *) dest)->height != expected_depth))
3805      return IMGTOOLERR_CORRUPTIMAGE;
3806
3807   return IMGTOOLERR_SUCCESS;
3808}
3809
3810/*
3811   BT_node_get_record
3812
3813   Extract a raw record from a B-tree node
3814
3815   BTref (I/O): open B-tree file handle
3816   node_buf (I): buffer with the node the record should be extracted from
3817   recnum (I): index of record to read
3818   rec_ptr (O): set to point to start of record (key + data)
3819   rec_len (O): set to total length of record (key + data)
3820
3821   Return imgtool error code
3822*/
3823static imgtoolerr_t BT_node_get_record(mac_BTref *BTref, void *node_buf, unsigned recnum, void **rec_ptr, int *rec_len)
3824{
3825   UINT16 node_numRecords = get_UINT16BE(((BTNodeHeader *) node_buf)->numRecords);
3826   UINT16 offset;
3827   UINT16 next_offset;
3828
3829   if (recnum >= node_numRecords)
3830      return IMGTOOLERR_UNEXPECTED;
3831
3832   offset = get_UINT16BE(((UINT16BE *)((UINT8 *) node_buf + BTref->nodeSize))[-recnum-1]);
3833   next_offset = get_UINT16BE(((UINT16BE *)((UINT8 *) node_buf + BTref->nodeSize))[-recnum-2]);
3834
3835   if ((offset < sizeof(BTNodeHeader)) || (offset > BTref->nodeSize-2*node_numRecords)
3836         || (next_offset < sizeof(BTNodeHeader)) || (next_offset > BTref->nodeSize-2*node_numRecords)
3837         || (offset & 1) || (next_offset & 1)
3838         || (offset > next_offset))
3839      return IMGTOOLERR_CORRUPTIMAGE;
3840
3841   *rec_ptr = (UINT8 *)node_buf + offset;
3842   *rec_len = next_offset - offset;
3843
3844   return IMGTOOLERR_SUCCESS;
3845}
3846
3847/*
3848   BT_node_get_keyed_record
3849
3850   Extract a keyed record from a B-tree node.  Equivalent to
3851   BT_node_get_record, only we do extra checks.
3852
3853   BTref (I/O): open B-tree file handle
3854   node_buf (I): buffer with the node the record should be extracted from
3855   node_is_index (I): TRUE if node is index node
3856   recnum (I): index of record to read
3857   rec_ptr (O): set to point to start of record (key + data)
3858   rec_len (O): set to total length of record (key + data)
3859
3860   Return imgtool error code
3861*/
3862static imgtoolerr_t BT_node_get_keyed_record(mac_BTref *BTref, void *node_buf, int node_is_index, unsigned recnum, void **rec_ptr, int *rec_len)
3863{
3864   imgtoolerr_t err;
3865   void *lrec_ptr;
3866   int lrec_len;
3867   int key_len;
3868
3869   /* extract record */
3870   err = BT_node_get_record(BTref, node_buf, recnum, &lrec_ptr, &lrec_len);
3871   if (err)
3872      return err;
3873
3874   /* read key len */
3875   key_len = (BTref->attributes & btha_bigKeysMask)
3876            ? get_UINT16BE(* (UINT16BE *)lrec_ptr)
3877            : (* (UINT8 *)lrec_ptr);
3878
3879   /* check that key fits in record */
3880   if ((key_len + ((BTref->attributes & btha_bigKeysMask) ? 2 : 1)) > lrec_len)
3881      /* hurk! */
3882      return IMGTOOLERR_CORRUPTIMAGE;
3883
3884   if (key_len > BTref->maxKeyLength)
3885      return IMGTOOLERR_CORRUPTIMAGE;
3886
3887   if (node_is_index && (! (BTref->attributes & btha_variableIndexKeysMask)) && (key_len != BTref->maxKeyLength))
3888      return IMGTOOLERR_CORRUPTIMAGE;
3889
3890   if (rec_ptr)
3891      *rec_ptr = lrec_ptr;
3892   if (rec_len)
3893      *rec_len = lrec_len;
3894
3895   return IMGTOOLERR_SUCCESS;
3896}
3897
3898/*
3899   BT_get_keyed_record_data
3900
3901   extract data from a keyed record
3902
3903   BTref (I/O): open B-tree file handle
3904   rec_ptr (I): point to start of record (key + data)
3905   rec_len (I): total length of record (key + data)
3906   data_ptr (O): set to point to record data
3907   data_len (O): set to length of record data
3908
3909   Return imgtool error code
3910*/
3911static imgtoolerr_t BT_get_keyed_record_data(mac_BTref *BTref, void *rec_ptr, int rec_len, void **data_ptr, int *data_len)
3912{
3913   int lkey_len;
3914   int data_offset;
3915
3916   /* read key len */
3917   lkey_len = (BTref->attributes & btha_bigKeysMask)
3918            ? get_UINT16BE(* (UINT16BE *)rec_ptr)
3919            : (* (UINT8 *)rec_ptr);
3920
3921   /* compute offset to data record */
3922   data_offset = lkey_len + ((BTref->attributes & btha_bigKeysMask) ? 2 : 1);
3923   if (data_offset > rec_len)
3924      /* hurk! */
3925      return IMGTOOLERR_CORRUPTIMAGE;
3926   /* fix alignment */
3927   if (data_offset & 1)
3928      data_offset++;
3929
3930   if (data_ptr)
3931      *data_ptr = (UINT8 *)rec_ptr + data_offset;
3932   if (data_len)
3933      *data_len = (rec_len > data_offset) ? rec_len-data_offset : 0;
3934
3935   return IMGTOOLERR_SUCCESS;
3936}
3937
3938/*
3939   BT_check
3940
3941   Check integrity of a complete B-tree
3942
3943   BTref (I/O): open B-tree file handle
3944   is_extent (I): TRUE if we are opening the extent B-tree (we want to do
3945      extra checks in this case because the extent B-Tree may include extent
3946      records for the extent B-tree itself, and if an extent record for the
3947      extent B-tree is located in an extent that has not been defined by
3948      previous extent records, then we can never retreive this extent record)
3949
3950   Return imgtool error code
3951*/
3952static imgtoolerr_t BT_check(mac_BTref *BTref, int is_extent)
3953{
3954   UINT16 node_numRecords;
3955   BTHeaderRecord *header_rec;
3956   UINT8 *bitmap;
3957   struct
3958   {
3959      void *buf;
3960      UINT32 node_num;
3961      UINT32 cur_rec;
3962      UINT32 num_recs;
3963   } *data_nodes;
3964   int i, j;
3965   UINT32 cur_node, prev_node;
3966   void *rec1, *rec2;
3967   int rec1_len, rec2_len;
3968   void *rec1_data;
3969   int rec1_data_len;
3970   UINT32 totalNodes, lastLeafNode;
3971   UINT32 freeNodes;
3972   int compare_result;
3973   UINT32 map_count, map_len;
3974   UINT32 run_len;
3975   UINT32 run_bit_len;
3976   UINT32 actualFreeNodes;
3977   imgtoolerr_t err;
3978   UINT32 maxExtentAB = 0, maxExtentNode = 0, extentEOL = 0;   /* if is_extent is TRUE */
3979
3980   if (is_extent)
3981   {
3982      switch (BTref->fileref.l2_img->format)
3983      {
3984      case L2I_MFS:
3985         /* MFS does not feature any extents B-tree! */
3986         return IMGTOOLERR_UNEXPECTED;
3987
3988      case L2I_HFS:
3989         maxExtentAB = 0;
3990         for (j=0; j<3; j++)
3991            maxExtentAB += get_UINT16BE(BTref->fileref.u.hfs.extents[j].numABlks);
3992         maxExtentNode = (UINT64)maxExtentAB * 512 * BTref->fileref.l2_img->blocksperAB
3993                              / BTref->nodeSize;
3994         extentEOL = FALSE;
3995         break;
3996      }
3997   }
3998
3999   /* read header node */
4000   if ((! is_extent) || (0 < maxExtentNode))
4001      err = BT_read_node(BTref, 0, btnk_headerNode, 0, BTref->node_buf);
4002   else
4003      err = IMGTOOLERR_CORRUPTIMAGE;
4004   if (err)
4005      return err;
4006
4007   /* check we have enough records */
4008   node_numRecords = get_UINT16BE(((BTNodeHeader *) BTref->node_buf)->numRecords);
4009   if (node_numRecords < 3)
4010      return IMGTOOLERR_CORRUPTIMAGE;
4011
4012   /* get header record */
4013   err = BT_node_get_record(BTref, BTref->node_buf, 0, &rec1, &rec1_len);
4014   if (err)
4015      return err;
4016   header_rec = (BTHeaderRecord *)rec1;
4017
4018   /* check length of header record */
4019   if (rec1_len < sizeof(BTHeaderRecord))
4020      return IMGTOOLERR_CORRUPTIMAGE;
4021
4022   totalNodes = get_UINT32BE(header_rec->totalNodes);
4023   if (totalNodes == 0)
4024      /* we need at least one header node */
4025      return IMGTOOLERR_CORRUPTIMAGE;
4026   lastLeafNode = get_UINT32BE(header_rec->lastLeafNode);
4027   freeNodes = get_UINT32BE(header_rec->freeNodes);
4028
4029   /* check file length */
4030   if ((BTref->nodeSize * totalNodes) > BTref->fileref.pLen)
4031      return IMGTOOLERR_CORRUPTIMAGE;
4032
4033   /* initialize for the function postlog ("bail:" tag) */
4034   err = IMGTOOLERR_SUCCESS;
4035   bitmap = NULL;
4036   data_nodes = NULL;
4037
4038   /* alloc buffer for reconstructed bitmap */
4039   map_len = (totalNodes + 7) / 8;
4040   bitmap = malloc(map_len);
4041   if (! bitmap)
4042      return IMGTOOLERR_OUTOFMEMORY;
4043   memset(bitmap, 0, map_len);
4044
4045   /* check B-tree data nodes (i.e. index and leaf nodes) */
4046   if (BTref->treeDepth == 0)
4047   {
4048      /* B-tree is empty */
4049      if (BTref->rootNode || BTref->firstLeafNode || lastLeafNode)
4050      {
4051         err = IMGTOOLERR_OUTOFMEMORY;
4052         goto bail;
4053      }
4054   }
4055   else
4056   {
4057      /* alloc array of buffers for catalog data nodes */
4058      data_nodes = malloc(sizeof(data_nodes[0]) * BTref->treeDepth);
4059      if (! data_nodes)
4060      {
4061         err = IMGTOOLERR_OUTOFMEMORY;
4062         goto bail;
4063      }
4064      for (i=0; i<BTref->treeDepth; i++)
4065         data_nodes[i].buf = NULL;   /* required for function postlog to work should next loop fail */
4066      for (i=0; i<BTref->treeDepth; i++)
4067      {
4068         data_nodes[i].buf = malloc(BTref->nodeSize);
4069         if (!data_nodes[i].buf)
4070         {
4071            err = IMGTOOLERR_OUTOFMEMORY;
4072            goto bail;
4073         }
4074      }
4075
4076      /* read first data nodes */
4077      cur_node = BTref->rootNode;
4078      for (i=BTref->treeDepth-1; i>=0; i--)
4079      {
4080         /* check node index */
4081         if (cur_node >= totalNodes)
4082         {
4083            err = IMGTOOLERR_CORRUPTIMAGE;
4084            goto bail;
4085         }
4086         /* check that node has not been used for another purpose */
4087         /* this check is unecessary because the current consistency checks
4088         that forward and back linking match and that node height is correct
4089         are enough to detect such errors */
4090         /*if (bitmap[cur_node >> 3] & (0x80 >> (cur_node & 7)))
4091         {
4092            err = IMGTOOLERR_CORRUPTIMAGE;
4093            goto bail;
4094         }*/
4095         /* add node in bitmap */
4096         bitmap[cur_node >> 3] |= (0x80 >> (cur_node & 7));
4097         /* read node */
4098         if ((! is_extent) || (cur_node < maxExtentNode))
4099            err = BT_read_node(BTref, cur_node, i ? btnk_indexNode : btnk_leafNode, i+1, data_nodes[i].buf);
4100         else
4101            err = IMGTOOLERR_CORRUPTIMAGE;
4102         if (err)
4103            goto bail;
4104         /* check that it is the first node at this level */
4105         if (get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->bLink))
4106         {
4107            err = IMGTOOLERR_CORRUPTIMAGE;
4108            goto bail;
4109         }
4110         /* fill other fields */
4111         data_nodes[i].node_num = cur_node;
4112         data_nodes[i].cur_rec = 0;
4113         data_nodes[i].num_recs = get_UINT16BE(((BTNodeHeader *) data_nodes[i].buf)->numRecords);
4114         /* check that there is at least one record */
4115         if (data_nodes[i].num_recs == 0)
4116         {
4117            err = IMGTOOLERR_CORRUPTIMAGE;
4118            goto bail;
4119         }
4120
4121         /* iterate to next level if applicable */
4122         if (i != 0)
4123         {
4124            /* extract first record */
4125            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, TRUE, 0, &rec1, &rec1_len);
4126            if (err)
4127               goto bail;
4128
4129            /* extract record data ptr */
4130            err = BT_get_keyed_record_data(BTref, rec1, rec1_len, &rec1_data, &rec1_data_len);
4131            if (err)
4132               goto bail;
4133            if (rec1_data_len < sizeof(UINT32BE))
4134            {
4135               err = IMGTOOLERR_CORRUPTIMAGE;
4136               goto bail;
4137            }
4138
4139            /* iterate to next level */
4140            cur_node = get_UINT32BE(* (UINT32BE *)rec1_data);
4141         }
4142      }
4143
4144      /* check that a) the root node has no successor, and b) that we have really
4145      read the first leaf node */
4146      if (get_UINT32BE(((BTNodeHeader *) data_nodes[BTref->treeDepth-1].buf)->fLink)
4147            || (cur_node != BTref->firstLeafNode))
4148      {
4149         err = IMGTOOLERR_CORRUPTIMAGE;
4150         goto bail;
4151      }
4152
4153      /* check that keys are ordered correctly */
4154      while (1)
4155      {
4156         /* iterate through parent nodes */
4157         i = 0;
4158         while ((i<BTref->treeDepth) && ((data_nodes[i].cur_rec == 0) || (data_nodes[i].cur_rec == data_nodes[i].num_recs)))
4159         {
4160            /* read next node if necessary */
4161            if (data_nodes[i].cur_rec == data_nodes[i].num_recs)
4162            {
4163               /* get link to next node */
4164               cur_node = get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->fLink);
4165               if (cur_node == 0)
4166               {
4167                  if (i == 0)
4168                     /* normal End of List */
4169                     goto end_of_list;
4170                  else
4171                  {
4172                     /* error */
4173                     err = IMGTOOLERR_CORRUPTIMAGE;
4174                     goto bail;
4175                  }
4176               }
4177               /* add node in bitmap */
4178               bitmap[cur_node >> 3] |= (0x80 >> (cur_node & 7));
4179               /* read node */
4180               if ((! is_extent) || (cur_node < maxExtentNode))
4181                  err = BT_read_node(BTref, cur_node, i ? btnk_indexNode : btnk_leafNode, i+1, data_nodes[i].buf);
4182               else
4183                  err = IMGTOOLERR_CORRUPTIMAGE;
4184               if (err)
4185                  goto bail;
4186               /* check that backward linking match forward linking */
4187               if (get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->bLink) != data_nodes[i].node_num)
4188               {
4189                  err = IMGTOOLERR_CORRUPTIMAGE;
4190                  goto bail;
4191               }
4192               /* fill other fields */
4193               data_nodes[i].node_num = cur_node;
4194               data_nodes[i].cur_rec = 0;
4195               data_nodes[i].num_recs = get_UINT16BE(((BTNodeHeader *) data_nodes[i].buf)->numRecords);
4196               /* check that there is at least one record */
4197               if (data_nodes[i].num_recs == 0)
4198               {
4199                  err = IMGTOOLERR_CORRUPTIMAGE;
4200                  goto bail;
4201               }
4202               /* next test is not necessary because we have checked that
4203               the root node has no successor */
4204               /*if (i < BTref->treeDepth-1)
4205               {*/
4206                  data_nodes[i+1].cur_rec++;
4207               /*}
4208               else
4209               {
4210                  err = IMGTOOLERR_CORRUPTIMAGE;
4211                  goto bail;
4212               }*/
4213            }
4214            i++;
4215         }
4216
4217         if (is_extent && !extentEOL)
4218         {
4219            /* extract current leaf record and update maxExtentAB and
4220            maxExtentNode */
4221            hfs_extentKey *extentKey;
4222            hfs_extent *extentData;
4223
4224            /* extract current leaf record */
4225            err = BT_node_get_keyed_record(BTref, data_nodes[0].buf, FALSE, data_nodes[0].cur_rec, &rec1, &rec1_len);
4226            if (err)
4227               goto bail;
4228
4229            extentKey = rec1;
4230            if ((extentKey->keyLength < 7) || (extentKey->forkType != 0) || (get_UINT32BE(extentKey->fileID) != 3)
4231                  || (get_UINT16BE(extentKey->startBlock) != maxExtentAB))
4232               /* the key is corrupt or does not concern the extent
4233               B-tree: set the extentEOL flag so that we stop looking for
4234               further extent records for the extent B-tree */
4235               extentEOL = TRUE;
4236            else
4237            {   /* this key concerns the extent B-tree: update maxExtentAB
4238               and maxExtentNode */
4239               /* extract record data ptr */
4240               err = BT_get_keyed_record_data(BTref, rec1, rec1_len, &rec1_data, &rec1_data_len);
4241               if (err)
4242                  goto bail;
4243               if (rec1_data_len < sizeof(hfs_extent)*3)
4244                  /* the record is corrupt: set the extentEOL flag so
4245                  that we stop looking for further extent records for the
4246                  extent B-tree */
4247                  extentEOL = TRUE;
4248               else
4249               {
4250                  extentData = rec1_data;
4251
4252                  for (j=0; j<3; j++)
4253                     maxExtentAB += get_UINT16BE(extentData[j].numABlks);
4254                  maxExtentNode = (UINT64)maxExtentAB * 512 * BTref->fileref.l2_img->blocksperAB
4255                                    / BTref->nodeSize;
4256               }
4257            }
4258            if (extentEOL)
4259            {
4260               /* check that the extent B-Tree has been defined entirely */
4261               if (maxExtentNode < totalNodes)
4262               {   /* no good */
4263                  err = IMGTOOLERR_CORRUPTIMAGE;
4264                  goto bail;
4265               }
4266            }
4267         }
4268
4269         if (i<BTref->treeDepth)
4270         {
4271            /* extract current record */
4272            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, i > 0, data_nodes[i].cur_rec, &rec1, &rec1_len);
4273            if (err)
4274               goto bail;
4275
4276            /* extract previous record */
4277            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, i > 0, data_nodes[i].cur_rec-1, &rec2, &rec2_len);
4278            if (err)
4279               goto bail;
4280
4281            /* check that it is sorted correctly */
4282            compare_result = (*BTref->key_compare_func)(rec1, rec2);
4283            if (compare_result <= 0)
4284            {
4285               err = IMGTOOLERR_CORRUPTIMAGE;
4286               goto bail;
4287            }
4288
4289            i--;
4290         }
4291         else
4292         {
4293            i--;
4294            if (i>0)
4295            {   /* extract first record of root if it is an index node */
4296               err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, TRUE, data_nodes[i].cur_rec, &rec1, &rec1_len);
4297               if (err)
4298                  goto bail;
4299            }
4300            i--;
4301         }
4302
4303         while (i>=0)
4304         {
4305            /* extract first record of current level */
4306            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, i > 0, data_nodes[i].cur_rec, &rec2, &rec2_len);
4307            if (err)
4308               goto bail;
4309
4310            /* compare key with key of current record of upper level */
4311            compare_result = (*BTref->key_compare_func)(rec1, rec2);
4312            if (compare_result != 0)
4313            {
4314               err = IMGTOOLERR_CORRUPTIMAGE;
4315               goto bail;
4316            }
4317
4318            /* extract record data ptr */
4319            err = BT_get_keyed_record_data(BTref, rec1, rec1_len, &rec1_data, &rec1_data_len);
4320            if (err)
4321               goto bail;
4322            if (rec1_data_len < sizeof(UINT32BE))
4323            {
4324               err = IMGTOOLERR_CORRUPTIMAGE;
4325               goto bail;
4326            }
4327            cur_node = get_UINT32BE(* (UINT32BE *)rec1_data);
4328
4329            /* compare node index with data of current record of upper
4330            level */
4331            if (cur_node != data_nodes[i].node_num)
4332            {
4333               err = IMGTOOLERR_CORRUPTIMAGE;
4334               goto bail;
4335            }
4336
4337            /* iterate to next level */
4338            rec1 = rec2;
4339            rec1_len = rec2_len;
4340            i--;
4341         }
4342
4343         /* next leaf record */
4344         data_nodes[0].cur_rec++;
4345      }
4346
4347end_of_list:
4348      /* check that we are at the end of list for each index level */
4349      for (i=1; i<BTref->treeDepth; i++)
4350      {
4351         if ((data_nodes[i].cur_rec != (data_nodes[i].num_recs-1))
4352               || get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->fLink))
4353         {
4354            err = IMGTOOLERR_CORRUPTIMAGE;
4355            goto bail;
4356         }
4357      }
4358      /* check that the last leaf node is what it is expected to be */
4359      if (data_nodes[0].node_num != lastLeafNode)
4360      {
4361         err = IMGTOOLERR_CORRUPTIMAGE;
4362         goto bail;
4363      }
4364   }
4365
4366   /* check map node chain */
4367   cur_node = 0;   /* node 0 is the header node... */
4368   bitmap[0] |= 0x80;
4369   /* check back linking */
4370   if (get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->bLink))
4371   {
4372      err = IMGTOOLERR_CORRUPTIMAGE;
4373      goto bail;
4374   }
4375   /* get pointer to next node */
4376   cur_node = get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->fLink);
4377   while (cur_node != 0)
4378   {
4379      /* save node address */
4380      prev_node = cur_node;
4381      /* check that node has not been used for another purpose */
4382      /* this check is unecessary because the current consistency checks that
4383      forward and back linking match and that node height is correct are
4384      enough to detect such errors */
4385      /*if (bitmap[cur_node >> 3] & (0x80 >> (cur_node & 7)))
4386      {
4387         err = IMGTOOLERR_CORRUPTIMAGE;
4388         goto bail;
4389      }*/
4390      /* add node in bitmap */
4391      bitmap[cur_node >> 3] |= (0x80 >> (cur_node & 7));
4392      /* read map node */
4393      if ((! is_extent) || (cur_node < maxExtentNode))
4394         err = BT_read_node(BTref, cur_node, btnk_mapNode, 0, BTref->node_buf);
4395      else
4396         err = IMGTOOLERR_CORRUPTIMAGE;
4397      if (err)
4398         goto bail;
4399      /* check back linking */
4400      if (get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->bLink) != prev_node)
4401      {
4402         err = IMGTOOLERR_CORRUPTIMAGE;
4403         goto bail;
4404      }
4405      /* get pointer to next node */
4406      cur_node = get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->fLink);
4407   }
4408
4409   /* re-read header node */
4410   err = BT_read_node(BTref, 0, btnk_headerNode, 0, BTref->node_buf);
4411   if (err)
4412      goto bail;
4413
4414   /* get header bitmap record */
4415   err = BT_node_get_record(BTref, BTref->node_buf, 2, &rec1, &rec1_len);
4416   if (err)
4417      goto bail;
4418
4419   /* check bitmap, iterating map nodes */
4420   map_count = 0;
4421   actualFreeNodes = 0;
4422   while (map_count < map_len)
4423   {
4424      /* compute compare len */
4425      run_len = rec1_len;
4426      if (run_len > (map_len-map_count))
4427         run_len = map_len-map_count;
4428      /* check that all used nodes are marked as such in the B-tree bitmap */
4429      for (i=0; i<run_len; i++)
4430         if (bitmap[map_count+i] & ~((UINT8 *)rec1)[i])
4431         {
4432            err = IMGTOOLERR_CORRUPTIMAGE;
4433            goto bail;
4434         }
4435      /* count free nodes */
4436      run_bit_len = rec1_len*8;
4437      if (run_bit_len > (totalNodes-map_count*8))
4438         run_bit_len = totalNodes-map_count*8;
4439      for (i=0; i<run_bit_len; i++)
4440         if (! (((UINT8 *)rec1)[i>>3] & (0x80 >> (i & 7))))
4441            actualFreeNodes++;
4442      map_count += run_len;
4443      /* read next map node if required */
4444      if (map_count < map_len)
4445      {
4446         /* get pointer to next node */
4447         cur_node = get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->fLink);
4448         if (cur_node == 0)
4449         {
4450            err = IMGTOOLERR_CORRUPTIMAGE;
4451            goto bail;
4452         }
4453         /* read map node */
4454         err = BT_read_node(BTref, cur_node, btnk_mapNode, 0, BTref->node_buf);
4455         if (err)
4456            goto bail;
4457         /* get map record */
4458         err = BT_node_get_record(BTref, BTref->node_buf, 0, &rec1, &rec1_len);
4459         if (err)
4460            goto bail;
4461         header_rec = (BTHeaderRecord *)rec1;
4462      }
4463   }
4464
4465   /* check free node count */
4466   if (freeNodes != actualFreeNodes)
4467      return IMGTOOLERR_CORRUPTIMAGE;
4468
4469bail:
4470   /* free buffers */
4471   if (data_nodes)
4472   {
4473      for (i=0; i<BTref->treeDepth; i++)
4474         if (data_nodes[i].buf)
4475            free(data_nodes[i].buf);
4476      free(data_nodes);
4477   }
4478   if (bitmap)
4479      free(bitmap);
4480
4481   return err;
4482}
4483
4484/*
4485   BT_search_leaf_rec
4486
4487   Search for a given key in a B-Tree.  If exact match found, returns
4488   corresponding leaf record.  Otherwise, may return the greatest record less
4489   than the requested key (of course, this will fail if the key is lower than
4490   all keys in the B-Tree).
4491
4492   BTref (I/O): open B-tree file handle
4493   search_key (I): key to search the B-Tree for
4494   node_ID (O): set to the node ID of the node the record is located in (may
4495      be NULL)
4496   record_ID (O): set to the index of the record in the node (may be NULL)
4497   record_ptr (O): set to point to record in node buffer (may be NULL)
4498   record_len (O): set to total record len (may be NULL)
4499   search_exact_match (I): if TRUE, the function will search for a record
4500      equal to search_key; if FALSE, the function will search for the
4501      greatest record less than or equal to search_key
4502   match_found (O): set to TRUE if an exact match for search_key has been
4503      found (only makes sense if search_exact_match is FALSE) (may be NULL)
4504
4505   Return imgtool error code
4506*/
4507static imgtoolerr_t BT_search_leaf_rec(mac_BTref *BTref, const void *search_key,
4508                              UINT32 *node_ID, int *record_ID,
4509                              void **record_ptr, int *record_len,
4510                              int search_exact_match, int *match_found)
4511{
4512   imgtoolerr_t err;
4513   int i;
4514   UINT32 cur_node;
4515   void *cur_rec;
4516   int cur_rec_len;
4517   void *last_rec;
4518   int last_rec_len = 0;
4519   void *rec_data;
4520   int rec_data_len;
4521   int depth;
4522   UINT16 node_numRecords;
4523   int compare_result = 0;
4524
4525   /* start with root node */
4526   if ((BTref->rootNode == 0) || (BTref->treeDepth == 0))
4527      /* tree is empty */
4528      return ((BTref->rootNode == 0) == (BTref->treeDepth == 0))
4529               ? IMGTOOLERR_FILENOTFOUND
4530               : IMGTOOLERR_CORRUPTIMAGE;
4531
4532   cur_node = BTref->rootNode;
4533   depth = BTref->treeDepth;
4534
4535   while (1)
4536   {
4537      /* read current node */
4538      err = BT_read_node(BTref, cur_node, (depth > 1) ? btnk_indexNode : btnk_leafNode, depth, BTref->node_buf);
4539      if (err)
4540         return err;
4541
4542      /* search for key */
4543      node_numRecords = get_UINT16BE(((BTNodeHeader *) BTref->node_buf)->numRecords);
4544      last_rec = cur_rec = NULL;
4545      for (i=0; i<node_numRecords; i++)
4546      {
4547         err = BT_node_get_keyed_record(BTref, BTref->node_buf, depth > 1, i, &cur_rec, &cur_rec_len);
4548         if (err)
4549            return err;
4550
4551         compare_result = (*BTref->key_compare_func)(cur_rec, search_key);
4552         if (compare_result > 0)
4553            break;
4554         last_rec = cur_rec;
4555         last_rec_len = cur_rec_len;
4556         if (compare_result == 0)
4557            break;
4558      }
4559
4560      if (! last_rec)
4561      {   /* all keys are greater than the search key: the search key is
4562         nowhere in the tree */
4563         if (search_exact_match)
4564            return IMGTOOLERR_FILENOTFOUND;
4565
4566         if (match_found)
4567            *match_found = FALSE;
4568
4569         if (node_ID)
4570            *node_ID = 0;
4571
4572         if (record_ID)
4573            *record_ID = -1;
4574
4575         if (record_ptr)
4576            *record_ptr = NULL;
4577
4578         return IMGTOOLERR_SUCCESS;
4579      }
4580
4581      if (((BTNodeHeader *) BTref->node_buf)->kind == btnk_leafNode)
4582         /* leaf node -> end of search */
4583         break;
4584
4585      /* extract record data ptr */
4586      err = BT_get_keyed_record_data(BTref, last_rec, last_rec_len, &rec_data, &rec_data_len);
4587      if (err)
4588         return err;
4589      if (rec_data_len < sizeof(UINT32BE))
4590         return IMGTOOLERR_CORRUPTIMAGE;
4591
4592      /* iterate to next level */
4593      cur_node = get_UINT32BE(* (UINT32BE *)rec_data);
4594      depth--;
4595   }
4596
4597   if (compare_result != 0)
4598      /* key not found */
4599      if (search_exact_match)
4600         return IMGTOOLERR_FILENOTFOUND;
4601
4602   if (match_found)
4603      *match_found = (compare_result == 0);
4604
4605   if (node_ID)
4606      *node_ID = cur_node;
4607
4608   if (record_ID)
4609      *record_ID = i;
4610
4611   if (record_ptr)
4612      *record_ptr = last_rec;
4613
4614   if (record_len)
4615      *record_len = last_rec_len;
4616
4617   return IMGTOOLERR_SUCCESS;
4618}
4619
4620/*
4621   BT_leaf_rec_enumerator_open
4622
4623   Open enumerator for leaf records of a B-Tree
4624
4625   BTref (I/O): open B-tree file handle
4626   enumerator (O): B-Tree enumerator to open
4627
4628   Return imgtool error code
4629*/
4630static imgtoolerr_t BT_leaf_rec_enumerator_open(mac_BTref *BTref, BT_leaf_rec_enumerator *enumerator)
4631{
4632   enumerator->BTref = BTref;
4633   enumerator->cur_node = BTref->firstLeafNode;
4634   enumerator->cur_rec = 0;
4635
4636   return IMGTOOLERR_SUCCESS;
4637}
4638
4639/*
4640   BT_leaf_rec_enumerator_read
4641
4642   Read next leaf record of a B-Tree
4643
4644   enumerator (I/O): open B-Tree enumerator
4645
4646   Return imgtool error code
4647*/
4648static imgtoolerr_t BT_leaf_rec_enumerator_read(BT_leaf_rec_enumerator *enumerator, void **record_ptr, int *rec_len)
4649{
4650   UINT16 node_numRecords;
4651   imgtoolerr_t err;
4652
4653
4654   *record_ptr = NULL;
4655
4656   /* check EOList condition */
4657   if (enumerator->cur_node == 0)
4658      return IMGTOOLERR_SUCCESS;
4659
4660   /* read current node */
4661   err = BT_read_node(enumerator->BTref, enumerator->cur_node, btnk_leafNode, 1, enumerator->BTref->node_buf);
4662   if (err)
4663      return err;
4664   node_numRecords = get_UINT16BE(((BTNodeHeader *) enumerator->BTref->node_buf)->numRecords);
4665
4666   /* skip nodes until we find a record */
4667   while ((enumerator->cur_rec >= node_numRecords) && (enumerator->cur_node != 0))
4668   {
4669      enumerator->cur_node = get_UINT32BE(((BTNodeHeader *) enumerator->BTref->node_buf)->fLink);
4670      enumerator->cur_rec = 0;
4671
4672      /* read node */
4673      err = BT_read_node(enumerator->BTref, enumerator->cur_node, btnk_leafNode, 1, enumerator->BTref->node_buf);
4674      if (err)
4675         return err;
4676      node_numRecords = get_UINT16BE(((BTNodeHeader *) enumerator->BTref->node_buf)->numRecords);
4677   }
4678
4679   /* check EOList condition */
4680   if (enumerator->cur_node == 0)
4681      return IMGTOOLERR_SUCCESS;
4682
4683   /* get current record */
4684   err = BT_node_get_keyed_record(enumerator->BTref, enumerator->BTref->node_buf, FALSE, enumerator->cur_rec, record_ptr, rec_len);
4685   if (err)
4686      return err;
4687
4688   /* iterate to next record */
4689   enumerator->cur_rec++;
4690   if (enumerator->cur_rec >= node_numRecords)
4691   {   /* iterate to next node if last record (not required, but will improve
4692      performance on next iteration) */
4693      enumerator->cur_node = get_UINT32BE(((BTNodeHeader *) enumerator->BTref->node_buf)->fLink);
4694      enumerator->cur_rec = 0;
4695   }
4696   return IMGTOOLERR_SUCCESS;
4697}
4698
4699/*
4700   B-Tree extend EOF algorithm:
4701   * see if the bitmap will need to be extended
4702   * extend EOF by min 1 (if bitmap is large engough) or 2 (if bitmap needs
4703      to be extended) and max ClumpSiz (see extClpSiz and ctClpSiz in MDB)
4704      ***If we are extending the extent B-Tree, we need to defer the possible
4705      creation of an additional extent record, or we might enter an endless
4706      recursion loop***
4707
4708   Empty node alloc algorithm:
4709
4710   * see if there is any free node in B-tree bitmap
4711   * optionally, try to compact the B-tree if file is full
4712   * if file is still full, extend EOF and try again
4713   * mark new block as used and return its index
4714
4715
4716   Empty node delete algorithm:
4717
4718   * remove node from link list
4719   * mark node as free in the B-tree bitmap
4720   * optionally, if more than N% of the B-tree is free, compact the B-tree and
4721      free some disk space
4722   * Count nodes on this level; if there is only one left, delete parent index
4723      node and mark the relaining node as root; if it was the last leaf node,
4724      update header node with an empty B-tree; in either case, decrement tree
4725      depth
4726
4727
4728   Record shifting algorithm:
4729
4730   For a given node and its first non-empty successor node:
4731
4732   * compute how much free room there is in the node
4733   * see if the first record of the first non-empty successor can fit
4734   * if so, move it (i.e. delete the first record of the later node, and add a
4735      copy of it to the end of the former)
4736
4737
4738   Node merging algorithm
4739
4740   * Consider node and its predecessor.  If there is room, shift all records
4741      from later to former, then delete empty later node, and delete later
4742      record from parent index node.
4743
4744
4745   Node splitting algorithm (non-first)
4746
4747   * Consider node and its predecessor.  Create new middle node and split
4748      records in 3 even sets.  Update record for last node and insert record
4749      for middle node in parent index node.
4750
4751
4752   Node splitting algorithm (first node)
4753
4754   * Create new successor node, and split records in 2 1/3 and 2/3 sets.
4755      Insert record for later node in parent index node.
4756
4757
4758   Record delete algorithm:
4759
4760   * remove record from node
4761   * if record was first in node, test if node is now empty
4762      * if node is not empty, substitute key of deleted record with key of
4763         new head record in index tree
4764      * if node is empty, delete key of deleted record in index tree, then
4765         delete empty node
4766   * optionally, look the predecessor node.  Merge the two nodes if possible.
4767
4768
4769   Record insert algorithm:
4770
4771   * if there room, just insert new record in node; if new record is in first
4772      position, update record in parent index node
4773   * else consider predecessor: see if we can make enough room by shifting
4774      records.  If so, do shift records, insert new record, update record in
4775      parent index node
4776   * else split the nodes and insert record
4777*/
4778/*
4779   Possible additions:
4780
4781   Node compaction algorithm:
4782
4783   This algorithm can be executed with a specific start point and max number
4784   of nodes, or with all nodes on a level.
4785
4786   * see how many nodes we can save by shifting records left
4787   * if we will save at least one node, do shift as many records as possible
4788      (try to leave free space split homogeneously???)
4789*/
4790
4791/*static void*/
4792
4793#if 0
4794#pragma mark -
4795#pragma mark RESOURCE IMPLEMENTATION
4796#endif
4797
4798/*
4799   Resource manager
4800
4801   The resource manager stores arbitrary chunks of data (resource) identified
4802   by a type/id pair.  The resource type is a 4-char code, which generally
4803   implies the format of the data (e.g. 'PICT' is for a quickdraw picture,
4804   'STR ' for a macintosh string, 'CODE' for 68k machine code, etc).  The
4805   resource id is a signed 16-bit number that uniquely identifies each
4806   resource of a given type.  Note that, with most resource types, resources
4807   with id < 128 are system resources that are available to all applications,
4808   whereas resources with id >= 128 are application resources visible only to
4809   the application that defines them.
4810
4811   Each resource can optionally have a resource name, which is a macintosh
4812   string of 255 chars at most.
4813
4814   Limits:
4815   16MBytes of data
4816   64kbytes of type+reference lists
4817   64kbytes of resource names
4818
4819   The Macintosh toolbox can open several resource files simulteanously to
4820   overcome these restrictions.
4821
4822   Resources are used virtually everywhere in the Macintosh Toolbox, so it is
4823   no surprise that file comments and MFS folders are stored in resource files.
4824*/
4825
4826/*
4827   Resource header
4828*/
4829typedef struct rsrc_header
4830{
4831   UINT32BE data_offs;      /* Offset from beginning of resource fork to resource data */
4832   UINT32BE map_offs;      /* Offset from beginning of resource fork to resource map */
4833   UINT32BE data_len;      /* Length of resource data */
4834   UINT32BE map_len;      /* Length of resource map */
4835} rsrc_header;
4836
4837/*
4838   Resource data: each data entry is preceded by its len (UINT32BE)
4839   Offset to specific data fields are gotten from the resource map
4840*/
4841
4842/*
4843   Resource map:
4844*/
4845typedef struct rsrc_map_header
4846{
4847   rsrc_header reserved0;   /* Reserved for copy of resource header */
4848   UINT32BE reserved1;      /* Reserved for handle to next resource map */
4849   UINT16BE reserved2;      /* Reserved for file reference number */
4850
4851   UINT16BE attr;         /* Resource fork attributes */
4852   UINT16BE typelist_offs;   /* Offset from beginning of map to resource type list */
4853   UINT16BE namelist_offs;   /* Offset from beginning of map to resource name list */
4854   UINT16BE type_count;   /* Number of types in the map minus 1 */
4855                     /* This is actually part of the type list, which matters for offsets */
4856} rsrc_map_header;
4857
4858/*
4859   Resource type list entry
4860*/
4861typedef struct rsrc_type_entry
4862{
4863   UINT32BE type;         /* Resource type */
4864   UINT16BE ref_count;      /* Number of resources of this type in map minus 1 */
4865   UINT16BE ref_offs;      /* Offset from beginning of resource type list to reference list for this type */
4866} rsrc_type_entry;
4867
4868/*
4869   Resource reference list entry
4870*/
4871typedef struct rsrc_ref_entry
4872{
4873   UINT16BE id;         /* Resource ID */
4874   UINT16BE name_offs;      /* Offset from beginning of resource name list to resource name */
4875                     /* (-1 if none) */
4876   UINT8 attr;            /* Resource attributes */
4877   UINT24BE data_offs;      /* Offset from beginning of resource data to data for this resource */
4878   UINT32BE reserved;      /* Reserved for handle to resource */
4879} rsrc_ref_entry;
4880
4881/*
4882   Resource name list entry: this is just a standard macintosh string
4883*/
4884
4885typedef struct mac_resfileref
4886{
4887   mac_fileref fileref;   /* open resource fork ref (you may open resources
4888                        files in data fork, too, if you ever need to,
4889                        but Classic MacOS never does such a thing
4890                        (MacOS X often does so, though)) */
4891   UINT32 data_offs;      /* Offset from beginning of resource file to resource data */
4892   UINT32 map_offs;      /* Offset from beginning of resource file to resource data */
4893
4894   UINT16 typelist_offs;   /* Offset from beginning of map to resource type list */
4895   UINT16 namelist_offs;   /* Offset from beginning of map to resource name list */
4896   UINT16 type_count;      /* Number of types in the map minus 1 */
4897                     /* This is actually part of the type list, which matters for offsets */
4898} mac_resfileref;
4899
4900#ifdef UNUSED_FUNCTION
4901/*
4902   resfile_open
4903
4904   Open a file as a resource file.  The file must be already open as a
4905   macintosh file.
4906
4907   resfileref (I/O): resource file handle to open (resfileref->fileref must
4908      have been opened previously)
4909
4910   Return imgtool error code
4911*/
4912static imgtoolerr_t resfile_open(mac_resfileref *resfileref)
4913{
4914   imgtoolerr_t err;
4915   rsrc_header header;
4916   rsrc_map_header map_header;
4917
4918   /* seek to resource header */
4919   err = mac_file_seek(&resfileref->fileref, 0);
4920   if (err)
4921      return err;
4922
4923   err = mac_file_read(&resfileref->fileref, sizeof(header), &header);
4924   if (err)
4925      return err;
4926
4927   resfileref->data_offs = get_UINT32BE(header.data_offs);
4928   resfileref->map_offs = get_UINT32BE(header.map_offs);
4929
4930   /* seek to resource map header */
4931   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs);
4932   if (err)
4933      return err;
4934
4935   err = mac_file_read(&resfileref->fileref, sizeof(map_header), &map_header);
4936   if (err)
4937      return err;
4938
4939   resfileref->typelist_offs = get_UINT16BE(map_header.typelist_offs);
4940   resfileref->namelist_offs = get_UINT16BE(map_header.namelist_offs);
4941   resfileref->type_count = get_UINT16BE(map_header.type_count);
4942
4943   return IMGTOOLERR_SUCCESS;
4944}
4945
4946/*
4947   resfile_get_entry
4948
4949   Get the resource entry in the resource map associated with a given type/id
4950   pair.
4951
4952   resfileref (I/O): open resource file handle
4953   type (I): type of the resource
4954   id (I): id of the resource
4955   entry (O): resource entry that has been read
4956
4957   Return imgtool error code
4958*/
4959static imgtoolerr_t resfile_get_entry(mac_resfileref *resfileref, UINT32 type, UINT16 id, rsrc_ref_entry *entry)
4960{
4961   imgtoolerr_t err;
4962   rsrc_type_entry type_entry;
4963   UINT16 ref_count;
4964   int i;
4965
4966   /* seek to resource type list in resource map */
4967   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs+resfileref->typelist_offs+2);
4968   if (err)
4969      return err;
4970
4971   if (resfileref->type_count == 0xffff)
4972      /* type list is empty */
4973      return IMGTOOLERR_FILENOTFOUND;
4974
4975   for (i=0; i<=resfileref->type_count; i++)
4976   {
4977      err = mac_file_read(&resfileref->fileref, sizeof(type_entry), &type_entry);
4978      if (err)
4979         return err;
4980      if (type == get_UINT32BE(type_entry.type))
4981         break;
4982   }
4983   if (i > resfileref->type_count)
4984      /* type not found in list */
4985      return IMGTOOLERR_FILENOTFOUND;
4986
4987   ref_count = get_UINT16BE(type_entry.ref_count);
4988
4989   /* seek to resource ref list for this type in resource map */
4990   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs+resfileref->typelist_offs+get_UINT16BE(type_entry.ref_offs));
4991   if (err)
4992      return err;
4993
4994   if (ref_count == 0xffff)
4995      /* ref list is empty */
4996      return IMGTOOLERR_FILENOTFOUND;
4997
4998   for (i=0; i<=ref_count; i++)
4999   {
5000      err = mac_file_read(&resfileref->fileref, sizeof(*entry), entry);
5001      if (err)
5002         return err;
5003      if (id == get_UINT16BE(entry->id))
5004         break;
5005   }
5006   if (i > ref_count)
5007      /* id not found in list */
5008      return IMGTOOLERR_FILENOTFOUND;
5009
5010   /* type+id have been found... */
5011   return IMGTOOLERR_SUCCESS;
5012}
5013
5014/*
5015   resfile_get_resname
5016
5017   Get the name of a resource.
5018
5019   resfileref (I/O): open resource file handle
5020   entry (I): resource entry in the resource map (returned by
5021      resfile_get_entry)
5022   string (O): resource name
5023
5024   Return imgtool error code
5025*/
5026static imgtoolerr_t resfile_get_resname(mac_resfileref *resfileref, const rsrc_ref_entry *entry, mac_str255 string)
5027{
5028   imgtoolerr_t err;
5029   UINT16 name_offs;
5030   UINT8 len;
5031
5032   name_offs = get_UINT16BE(entry->name_offs);
5033
5034   if (name_offs == 0xffff)
5035      /* ref list is empty */
5036      return IMGTOOLERR_UNEXPECTED;
5037
5038   /* seek to resource name in name list in resource map */
5039   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs+name_offs);
5040   if (err)
5041      return err;
5042
5043   /* get string length */
5044   err = mac_file_read(&resfileref->fileref, 1, &len);
5045   if (err)
5046      return err;
5047
5048   string[0] = len;
5049
5050   /* get string data */
5051   err = mac_file_read(&resfileref->fileref, len, string+1);
5052   if (err)
5053      return err;
5054
5055   return IMGTOOLERR_SUCCESS;
5056}
5057
5058/*
5059   resfile_get_reslen
5060
5061   Get the data length for a given resource.
5062
5063   resfileref (I/O): open resource file handle
5064   entry (I): resource entry in the resource map (returned by
5065      resfile_get_entry)
5066   len (O): resource length
5067
5068   Return imgtool error code
5069*/
5070static imgtoolerr_t resfile_get_reslen(mac_resfileref *resfileref, const rsrc_ref_entry *entry, UINT32 *len)
5071{
5072   imgtoolerr_t err;
5073   UINT32 data_offs;
5074   UINT32BE llen;
5075
5076   data_offs = get_UINT24BE(entry->data_offs);
5077
5078   /* seek to resource data in resource data section */
5079   err = mac_file_seek(&resfileref->fileref, resfileref->data_offs+data_offs);
5080   if (err)
5081      return err;
5082
5083   /* get data length */
5084   err = mac_file_read(&resfileref->fileref, sizeof(llen), &llen);
5085   if (err)
5086      return err;
5087
5088   *len = get_UINT32BE(llen);
5089
5090   return IMGTOOLERR_SUCCESS;
5091}
5092
5093/*
5094   resfile_get_resdata
5095
5096   Get the data for a given resource.
5097
5098   resfileref (I/O): open resource file handle
5099   entry (I): resource entry in the resource map (returned by
5100      resfile_get_entry)
5101   offset (I): offset the data should be read from, usually 0
5102   len (I): length of the data to read, usually the value returned by
5103      resfile_get_reslen
5104   dest (O): resource data
5105
5106   Return imgtool error code
5107*/
5108static imgtoolerr_t resfile_get_resdata(mac_resfileref *resfileref, const rsrc_ref_entry *entry, UINT32 offset, UINT32 len, void *dest)
5109{
5110   imgtoolerr_t err;
5111   UINT32 data_offs;
5112   UINT32BE llen;
5113
5114   data_offs = get_UINT24BE(entry->data_offs);
5115
5116   /* seek to resource data in resource data section */
5117   err = mac_file_seek(&resfileref->fileref, resfileref->data_offs+data_offs);
5118   if (err)
5119      return err;
5120
5121   /* get data length */
5122   err = mac_file_read(&resfileref->fileref, sizeof(llen), &llen);
5123   if (err)
5124      return err;
5125
5126   /* check that we do not ask to read more data than avalaible */
5127   if ((offset + len) > get_UINT32BE(llen))
5128      return IMGTOOLERR_UNEXPECTED;
5129
5130   if (offset)
5131   {   /* seek to resource data offset in resource data section */
5132      err = mac_file_seek(&resfileref->fileref, resfileref->data_offs+data_offs+4+offset);
5133      if (err)
5134         return err;
5135   }
5136
5137   /* get data */
5138   err = mac_file_read(&resfileref->fileref, len, dest);
5139   if (err)
5140      return err;
5141
5142   return IMGTOOLERR_SUCCESS;
5143}
5144#endif
5145
5146#if 0
5147#pragma mark -
5148#pragma mark DESKTOP FILE IMPLEMENTATION
5149#endif
5150/*
5151   All macintosh volumes have information stored in the desktop file or the
5152   desktop database.
5153
5154   Such information include file comments, copy of BNDL and FREF resources
5155   that describes supported file types for each application on the volume,
5156   copy of icons for each file type registered by each application on the
5157   volume, etc.  On MFS volumes, the list of folders is stored in the desktop
5158   file as well.
5159
5160
5161   There have been two implementations of the desktop metadata:
5162
5163   * The original desktop file.  The database is stored in the resource fork
5164      of a (usually invisible) file called "Desktop" (case may change
5165      according to system versions), located at the root of the volume.  The
5166      desktop file is used by System 6 and earlier for all volumes (unless
5167      Appleshare 2 is installed and the volume is shared IIRC), and by System
5168      7 and later for volumes smaller than 2MBytes (so that floppy disks
5169      remain fully compatible with earlier versions of system).  The desktop
5170      file is incompletely documented by Apple technote TB06.
5171
5172   * The desktop database.  The database is stored in the resource fork is
5173      stored in the data fork of two (usually invisible) files called
5174      "Desktop DF" and "Desktop DF".  The desktop database is used for
5175      volumes shared by Appleshare 2, and for most volumes under System 7 and
5176      later.  The format of these file is not documented AFAIK.
5177
5178
5179   The reasons for the introduction of the desktop database were:
5180   * the macintosh resource manager cannot share resource files, which was
5181      a problem for Appleshare
5182   * the macintosh resource manager is pretty limited (+/-16MByte of data and
5183      2727 resources at most), which was a problem for large hard disks with
5184      many programs/comments
5185*/
5186
5187#ifdef UNUSED_FUNCTION
5188/*
5189   get_comment
5190
5191   Get a comment from the Desktop file
5192
5193   l2_img (I): macintosh image the data should be read from
5194   id (I): comment id (from mfs_hashString(), or HFS FXInfo/DXInfo records)
5195   comment (O): comment that has been read
5196
5197   Return imgtool error code
5198*/
5199static imgtoolerr_t get_comment(mac_l2_imgref *l2_img, UINT16 id, mac_str255 comment)
5200{
5201   static const UINT8 desktop_fname[] = {'\7','D','e','s','k','t','o','p'};
5202   #define restype_FCMT (('F' << 24) | ('C' << 16) | ('M' << 8) | 'T')
5203   mac_resfileref resfileref;
5204   rsrc_ref_entry resentry;
5205   UINT32 reslen;
5206   imgtoolerr_t err;
5207
5208   /* open rsrc fork of file Desktop in root directory */
5209   err = mac_file_open(l2_img, 2, desktop_fname, rsrc_fork, &resfileref.fileref);
5210   if (err)
5211      return err;
5212
5213   /* open resource structures */
5214   err = resfile_open(&resfileref);
5215   if (err)
5216      return err;
5217
5218   /* look for resource FCMT #id */
5219   err = resfile_get_entry(&resfileref, restype_FCMT, id, &resentry);
5220   if (err)
5221      return err;
5222
5223   /* extract comment len */
5224   err = resfile_get_reslen(&resfileref, &resentry, &reslen);
5225   if (err)
5226      return err;
5227
5228   /* check comment len */
5229   if (reslen > 256)
5230      /* hurk */
5231      /*return IMGTOOLERR_CORRUPTIMAGE;*/
5232      /* people willing to extend the MFM comment field (you know, the kind
5233      of masochists that try to support 20-year-old OSes) might append extra
5234      fields, so we just truncate the resource */
5235      reslen = 256;
5236
5237   /* extract comment data */
5238   err = resfile_get_resdata(&resfileref, &resentry, 0, reslen, comment);
5239   if (err)
5240      return err;
5241
5242   /* phew, we are done! */
5243   return IMGTOOLERR_SUCCESS;
5244}
5245#endif
5246
5247#if 0
5248#pragma mark -
5249#pragma mark IMGTOOL MODULE IMPLEMENTATION
5250#endif
5251
5252#ifdef UNUSED_FUNCTION
5253static void mac_image_exit(imgtool_image *img);
5254#endif
5255static void mac_image_info(imgtool_image *img, char *string, size_t len);
5256static imgtoolerr_t mac_image_beginenum(imgtool_directory *enumeration, const char *path);
5257static imgtoolerr_t mac_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
5258static imgtoolerr_t mac_image_freespace(imgtool_partition *partition, UINT64 *size);
5259static imgtoolerr_t mac_image_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf);
5260static imgtoolerr_t mac_image_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions);
5261
5262#ifdef UNUSED_FUNCTION
5263/*
5264   close a mfs/hfs image
5265*/
5266static void mac_image_exit(imgtool_image *img)
5267{
5268   mac_l2_imgref *image = get_imgref(img);
5269
5270   mac_image_close(image);
5271}
5272#endif
5273
5274/*
5275   get basic information on a mfs/hfs image
5276
5277   Currently returns the volume name
5278*/
5279static void mac_image_info(imgtool_image *img, char *string, size_t len)
5280{
5281   mac_l2_imgref *image = get_imgref(img);
5282
5283   switch (image->format)
5284   {
5285   case L2I_MFS:
5286      mac_to_c_strncpy(string, len, image->u.mfs.volname);
5287      break;
5288
5289   case L2I_HFS:
5290      mac_to_c_strncpy(string, len, image->u.hfs.volname);
5291      break;
5292   }
5293}
5294
5295/*
5296   MFS/HFS catalog iterator, used when imgtool reads the catalog
5297*/
5298typedef struct mac_iterator
5299{
5300   mac_format format;
5301   mac_l2_imgref *l2_img;
5302   union
5303   {
5304      struct
5305      {
5306         mfs_dirref dirref;            /* open directory reference */
5307      } mfs;
5308      struct
5309      {
5310         hfs_cat_enumerator catref;      /* catalog file enumerator */
5311      } hfs;
5312   } u;
5313} mac_iterator;
5314
5315/*
5316   Open the disk catalog for enumeration
5317*/
5318static imgtoolerr_t mac_image_beginenum(imgtool_directory *enumeration, const char *path)
5319{
5320   mac_l2_imgref *image = get_imgref(imgtool_directory_image(enumeration));
5321   mac_iterator *iter = (mac_iterator *) imgtool_directory_extrabytes(enumeration);
5322   imgtoolerr_t err = IMGTOOLERR_UNEXPECTED;
5323
5324   iter->format = image->format;
5325   iter->l2_img = image;
5326
5327   switch (iter->format)
5328   {
5329   case L2I_MFS:
5330      err = mfs_dir_open(image, path, &iter->u.mfs.dirref);
5331      break;
5332
5333   case L2I_HFS:
5334      err = hfs_cat_open(image, path, &iter->u.hfs.catref);
5335      break;
5336   }
5337
5338   if (err)
5339      return err;
5340
5341   return IMGTOOLERR_SUCCESS;
5342}
5343
5344/*
5345   Enumerate disk catalog next entry (MFS)
5346*/
5347static imgtoolerr_t mfs_image_nextenum(mac_iterator *iter, imgtool_dirent *ent)
5348{
5349   mfs_dir_entry *cur_dir_entry;
5350   imgtoolerr_t err;
5351
5352
5353   assert(iter->format == L2I_MFS);
5354
5355   ent->corrupt = 0;
5356   ent->eof = 0;
5357
5358   err = mfs_dir_read(&iter->u.mfs.dirref, &cur_dir_entry);
5359   if (err)
5360   {
5361      /* error */
5362      ent->corrupt = 1;
5363      return err;
5364   }
5365   else if (!cur_dir_entry)
5366   {
5367      /* EOF */
5368      ent->eof = 1;
5369      return IMGTOOLERR_SUCCESS;
5370   }
5371
5372   /* copy info */
5373   mac_to_c_strncpy(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), cur_dir_entry->name);
5374   ent->filesize = get_UINT32BE(cur_dir_entry->dataPhysicalSize)
5375                  + get_UINT32BE(cur_dir_entry->rsrcPhysicalSize);
5376
5377   return IMGTOOLERR_SUCCESS;
5378}
5379
5380#if 0
5381/*
5382   Concatenate path elements in the reverse order
5383
5384   dest (O): destination buffer
5385   dest_cur_pos (I/O): current position in destination buffer (buffer is
5386      filled from end to start)
5387   dest_max_len (I): length of destination buffer (use length minus one if you
5388      want to preserve a trailing NUL character)
5389   src (I): source C string
5390*/
5391static void concat_fname(char *dest, int *dest_cur_pos, int dest_max_len, const char *src)
5392{
5393   static const char ellipsis[] = { '.', '.', '.' };
5394   int src_len = strlen(src);   /* number of chars from src to insert */
5395
5396   if (src_len <= *dest_cur_pos)
5397   {
5398      *dest_cur_pos -= src_len;
5399      memcpy(dest + *dest_cur_pos, src, src_len);
5400   }
5401   else
5402   {
5403      memcpy(dest, src + src_len - *dest_cur_pos, *dest_cur_pos);
5404      *dest_cur_pos = 0;
5405      memcpy(dest, ellipsis, (sizeof(ellipsis) <= dest_max_len)
5406                              ? sizeof(ellipsis)
5407                              : dest_max_len);
5408   }
5409}
5410#endif
5411
5412/*
5413   Enumerate disk catalog next entry (HFS)
5414*/
5415static imgtoolerr_t hfs_image_nextenum(mac_iterator *iter, imgtool_dirent *ent)
5416{
5417   hfs_catKey *catrec_key;
5418   hfs_catData *catrec_data;
5419   UINT16 dataRecType;
5420   imgtoolerr_t err;
5421   /* currently, the mac->C conversion transcodes one mac char with at most 3
5422   C chars */
5423   int cur_name_head;
5424
5425   assert(iter->format == L2I_HFS);
5426
5427   ent->corrupt = 0;
5428   ent->eof = 0;
5429
5430   do
5431   {
5432      err = hfs_cat_read(&iter->u.hfs.catref, &catrec_key, &catrec_data);
5433      if (err)
5434      {
5435         /* error */
5436         ent->corrupt = 1;
5437         return err;
5438      }
5439      else if (!catrec_key)
5440      {
5441         /* EOF */
5442         ent->eof = 1;
5443         return IMGTOOLERR_SUCCESS;
5444      }
5445      dataRecType = get_UINT16BE(catrec_data->dataType);
5446   } while (((dataRecType != hcrt_Folder) && (dataRecType != hcrt_File))
5447      || (get_UINT32BE(catrec_key->parID) != iter->u.hfs.catref.parID));
5448
5449   /* copy info */
5450   switch (get_UINT16BE(catrec_data->dataType))
5451   {
5452      case hcrt_Folder:
5453         ent->directory = 1;
5454         ent->filesize = 0;
5455         break;
5456
5457      case hcrt_File:
5458         ent->directory = 0;
5459         ent->filesize = get_UINT32BE(catrec_data->file.dataPhysicalSize)
5460            + get_UINT32BE(catrec_data->file.rsrcPhysicalSize);
5461         break;
5462   }
5463
5464   /* initialize file path buffer */
5465   cur_name_head = sizeof(ent->filename) / sizeof(ent->filename[0]);
5466   if (cur_name_head > 0)
5467   {
5468      cur_name_head--;
5469      ent->filename[cur_name_head] = '\0';
5470   }
5471
5472   /* insert folder/file name in buffer */
5473   mac_to_c_strncpy(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), catrec_key->cName);
5474//   concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, buf);
5475
5476#if 0
5477   /* extract parent directory ID */
5478   parID = get_UINT32BE(catrec_key->parID);
5479
5480   /* looping while (parID != 1) will display the volume name; looping while
5481   (parID != 2) won't */
5482   while (parID != /*1*/2)
5483   {
5484      /* search catalog for folder thread */
5485      err = hfs_cat_search(iter->l2_img, parID, mac_empty_str, &catrec_key, &catrec_data);
5486      if (err)
5487      {
5488         /* error */
5489         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, ":");
5490         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, "???");
5491
5492         memmove(ent->filename, ent->filename+cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - cur_name_head);
5493         ent->corrupt = 1;
5494         return err;
5495      }
5496
5497      dataRecType = get_UINT16BE(catrec_data->dataType);
5498
5499      if (dataRecType != hcrt_FolderThread)
5500      {
5501         /* error */
5502         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0])-1, ":");
5503         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0])-1, "???");
5504
5505         memmove(ent->filename, ent->filename+cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0])-cur_name_head);
5506         ent->corrupt = 1;
5507         return IMGTOOLERR_CORRUPTIMAGE;
5508      }
5509
5510      /* got folder thread record: insert the folder name at the start of
5511      file path, then iterate */
5512      mac_to_c_strncpy(buf, sizeof(buf), catrec_data->thread.nodeName);
5513      concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, ":");
5514      concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, buf);
5515
5516      /* extract parent directory ID */
5517      parID = get_UINT32BE(catrec_data->thread.parID);
5518   }
5519   memmove(ent->filename, ent->filename+cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) -cur_name_head);
5520#endif
5521   return IMGTOOLERR_SUCCESS;
5522}
5523
5524/*
5525   Enumerate disk catalog next entry
5526*/
5527static imgtoolerr_t mac_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
5528{
5529   imgtoolerr_t err;
5530   mac_iterator *iter = (mac_iterator *) imgtool_directory_extrabytes(enumeration);
5531
5532   switch (iter->format)
5533   {
5534      case L2I_MFS:
5535         err = mfs_image_nextenum(iter, ent);
5536         break;
5537
5538      case L2I_HFS:
5539         err = hfs_image_nextenum(iter, ent);
5540         break;
5541
5542      default:
5543         assert(1);
5544         err = IMGTOOLERR_UNEXPECTED;
5545         break;
5546   }
5547   return err;
5548}
5549
5550/*
5551   Compute free space on disk image in bytes
5552*/
5553static imgtoolerr_t mac_image_freespace(imgtool_partition *partition, UINT64 *size)
5554{
5555   imgtool_image *image = imgtool_partition_image(partition);
5556   *size = ((UINT64) get_imgref(image)->freeABs) * 512;
5557   return IMGTOOLERR_SUCCESS;
5558}
5559
5560#ifdef UNUSED_FUNCTION
5561static imgtoolerr_t mac_get_comment(mac_l2_imgref *image, mac_str255 filename, const mac_dirent *cat_info, mac_str255 comment)
5562{
5563   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
5564   UINT16 commentID;
5565
5566   comment[0] = '\0';
5567
5568   /* get comment from Desktop file */
5569   switch (image->format)
5570   {
5571      case L2I_MFS:
5572         commentID = mfs_hashString(filename);
5573         err = get_comment(image, commentID, comment);
5574         break;
5575
5576      case L2I_HFS:
5577         /* This is the way to get Finder comments in system <= 7.  Attached
5578         comments use another method, and Finder 8 uses yet another one. */
5579         commentID = get_UINT16BE(cat_info->flXFinderInfo.comment);
5580         if (commentID)
5581            err = get_comment(image, commentID, comment);
5582         break;
5583   }
5584   return err;
5585}
5586#endif
5587
5588
5589/*
5590   Extract a file from a disk image.
5591*/
5592static imgtoolerr_t mac_image_readfile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *destf)
5593{
5594   imgtoolerr_t err;
5595   imgtool_image *img = imgtool_partition_image(partition);
5596   mac_l2_imgref *image = get_imgref(img);
5597   UINT32 parID;
5598   mac_str255 filename;
5599   mac_dirent cat_info;
5600   mac_fileref fileref;
5601   UINT8 buf[512];
5602   UINT32 i, run_len, data_len;
5603   mac_fork_t fork_num;
5604
5605   err = mac_identify_fork(fork, &fork_num);
5606   if (err)
5607      return err;
5608
5609   /* resolve path and fetch file info from directory/catalog */
5610   err = mac_lookup_path(image, fpath, &parID, filename, &cat_info, FALSE);
5611   if (err)
5612      return err;
5613   if (cat_info.dataRecType != hcrt_File)
5614      return IMGTOOLERR_FILENOTFOUND;
5615
5616   /* open file */
5617   err = mac_file_open(image, parID, filename, fork_num ? rsrc_fork : data_fork, &fileref);
5618   if (err)
5619      return err;
5620
5621   data_len = fork_num ? cat_info.rsrcLogicalSize : cat_info.dataLogicalSize;
5622
5623   /* extract DF */
5624   i = 0;
5625   while(i < data_len)
5626   {
5627      run_len = MIN(data_len - i, sizeof(buf));
5628
5629      err = mac_file_read(&fileref, run_len, buf);
5630      if (err)
5631         return err;
5632      if (stream_write(destf, buf, run_len) != run_len)
5633         return IMGTOOLERR_WRITEERROR;
5634      i += run_len;
5635   }
5636
5637   return IMGTOOLERR_SUCCESS;
5638}
5639
5640/*
5641   Add a file to a disk image.
5642*/
5643static imgtoolerr_t mac_image_writefile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
5644{
5645   imgtool_image *img = imgtool_partition_image(partition);
5646   mac_l2_imgref *image = get_imgref(img);
5647   UINT32 parID;
5648   mac_str255 filename;
5649   mac_dirent cat_info;
5650   mac_fileref fileref;
5651   UINT32 fork_len;
5652   /*UINT16 commentID;
5653   mac_str255 comment;*/
5654   UINT8 buf[512];
5655   UINT32 i, run_len;
5656   imgtoolerr_t err;
5657   mac_fork_t fork_num;
5658
5659   (void) writeoptions;
5660
5661   if (image->format == L2I_HFS)
5662      return IMGTOOLERR_UNIMPLEMENTED;
5663
5664   err = mac_identify_fork(fork, &fork_num);
5665   if (err)
5666      return err;
5667
5668   /*if (header.version_old != 0)
5669      return IMGTOOLERR_UNIMPLEMENTED;*/
5670   /*mac_strcpy(filename, header.filename);*/
5671   memset(&cat_info, 0, sizeof(cat_info));
5672   set_UINT32BE(&cat_info.flFinderInfo.type, 0x3F3F3F3F);
5673   set_UINT32BE(&cat_info.flFinderInfo.creator, 0x3F3F3F3F);
5674   fork_len = stream_size(sourcef);
5675   /*comment[0] = get_UINT16BE(header.comment_len);*/   /* comment length */
5676   /* Next two fields are set to 0 with MFS volumes.  IIRC, 0 normally
5677   means system script: I don't think MFS stores the file name script code
5678   anywhere on disk, so it should be a reasonable approximation. */
5679
5680   /* create file */
5681   /* clear inited flag and file location in window */
5682   set_UINT16BE(&cat_info.flFinderInfo.flags, get_UINT16BE(cat_info.flFinderInfo.flags) & ~fif_hasBeenInited);
5683   set_UINT16BE(&cat_info.flFinderInfo.location.v, 0);
5684   set_UINT16BE(&cat_info.flFinderInfo.location.h, 0);
5685
5686   /* resolve path and create file */
5687   err = mac_lookup_path(image, fpath, &parID, filename, &cat_info, TRUE);
5688   if (err)
5689      return err;
5690
5691   /* open file fork */
5692   err = mac_file_open(image, parID, filename, (fork_num ? rsrc_fork : data_fork), &fileref);
5693   if (err)
5694      return err;
5695
5696   err = mac_file_seteof(&fileref, fork_len);
5697   if (err)
5698      return err;
5699
5700   /* extract fork */
5701   for (i=0; i<fork_len;)
5702   {
5703      run_len = fork_len - i;
5704      if (run_len > 512)
5705         run_len = 512;
5706      if (stream_read(sourcef, buf, run_len) != run_len)
5707         return IMGTOOLERR_READERROR;
5708      err = mac_file_write(&fileref, run_len, buf);
5709      if (err)
5710         return err;
5711      i += run_len;
5712   }
5713   return IMGTOOLERR_SUCCESS;
5714}
5715
5716
5717
5718static imgtoolerr_t mac_image_listforks(imgtool_partition *partition, const char *path, imgtool_forkent *ents, size_t len)
5719{
5720   imgtoolerr_t err;
5721   UINT32 parID;
5722   mac_str255 filename;
5723   mac_dirent cat_info;
5724   int fork_num = 0;
5725   imgtool_image *img = imgtool_partition_image(partition);
5726   mac_l2_imgref *image = get_imgref(img);
5727
5728   /* resolve path and fetch file info from directory/catalog */
5729   err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
5730   if (err)
5731      return err;
5732   if (cat_info.dataRecType != hcrt_File)
5733      return IMGTOOLERR_FILENOTFOUND;
5734
5735   /* specify data fork */
5736   ents[fork_num].type = FORK_DATA;
5737   ents[fork_num].forkname[0] = '\0';
5738   ents[fork_num].size = cat_info.dataLogicalSize;
5739   fork_num++;
5740
5741   if (cat_info.rsrcLogicalSize > 0)
5742   {
5743      /* specify the resource fork */
5744      ents[fork_num].type = FORK_RESOURCE;
5745      strcpy(ents[fork_num].forkname, "RESOURCE_FORK");
5746      ents[fork_num].size = cat_info.rsrcLogicalSize;
5747      fork_num++;
5748   }
5749
5750   ents[fork_num].type = FORK_END;
5751   return IMGTOOLERR_SUCCESS;
5752}
5753
5754
5755
5756static imgtoolerr_t mac_image_getattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, imgtool_attribute *values)
5757{
5758   imgtoolerr_t err;
5759   imgtool_image *img = imgtool_partition_image(partition);
5760   UINT32 parID;
5761   mac_str255 filename;
5762   mac_dirent cat_info;
5763   mac_l2_imgref *image = get_imgref(img);
5764   int i;
5765
5766   /* resolve path and fetch file info from directory/catalog */
5767   err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
5768   if (err)
5769      return err;
5770   if (cat_info.dataRecType != hcrt_File)
5771      return IMGTOOLERR_FILENOTFOUND;
5772
5773   for (i = 0; attrs[i]; i++)
5774   {
5775      switch(attrs[i])
5776      {
5777         case IMGTOOLATTR_INT_MAC_TYPE:
5778            values[i].i = get_UINT32BE(cat_info.flFinderInfo.type);
5779            break;
5780         case IMGTOOLATTR_INT_MAC_CREATOR:
5781            values[i].i = get_UINT32BE(cat_info.flFinderInfo.creator);
5782            break;
5783         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
5784            values[i].i = get_UINT16BE(cat_info.flFinderInfo.flags);
5785            break;
5786         case IMGTOOLATTR_INT_MAC_COORDX:
5787            values[i].i = get_UINT16BE(cat_info.flFinderInfo.location.h);
5788            break;
5789         case IMGTOOLATTR_INT_MAC_COORDY:
5790            values[i].i = get_UINT16BE(cat_info.flFinderInfo.location.v);
5791            break;
5792         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
5793            values[i].i = get_UINT16BE(cat_info.flFinderInfo.fldr);
5794            break;
5795         case IMGTOOLATTR_INT_MAC_ICONID:
5796            values[i].i = get_UINT16BE(cat_info.flXFinderInfo.iconID);
5797            break;
5798         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
5799            values[i].i = cat_info.flXFinderInfo.script;
5800            break;
5801         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
5802            values[i].i = cat_info.flXFinderInfo.XFlags;
5803            break;
5804         case IMGTOOLATTR_INT_MAC_COMMENTID:
5805            values[i].i = get_UINT16BE(cat_info.flXFinderInfo.comment);
5806            break;
5807         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
5808            values[i].i = get_UINT32BE(cat_info.flXFinderInfo.putAway);
5809            break;
5810
5811         case IMGTOOLATTR_TIME_CREATED:
5812            values[i].t = mac_crack_time(cat_info.createDate);
5813            break;
5814         case IMGTOOLATTR_TIME_LASTMODIFIED:
5815            values[i].t = mac_crack_time(cat_info.modifyDate);
5816            break;
5817      }
5818   }
5819   return IMGTOOLERR_SUCCESS;
5820}
5821
5822
5823
5824static imgtoolerr_t mac_image_setattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, const imgtool_attribute *values)
5825{
5826   imgtoolerr_t err;
5827   UINT32 parID;
5828   mac_str255 filename;
5829   mac_dirent cat_info;
5830   imgtool_image *img = imgtool_partition_image(partition);
5831   mac_l2_imgref *image = get_imgref(img);
5832   int i;
5833
5834   /* resolve path and fetch file info from directory/catalog */
5835   err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
5836   if (err)
5837      return err;
5838   if (cat_info.dataRecType != hcrt_File)
5839      return IMGTOOLERR_FILENOTFOUND;
5840
5841   for (i = 0; attrs[i]; i++)
5842   {
5843      switch(attrs[i])
5844      {
5845         case IMGTOOLATTR_INT_MAC_TYPE:
5846            set_UINT32BE(&cat_info.flFinderInfo.type, values[i].i);
5847            break;
5848         case IMGTOOLATTR_INT_MAC_CREATOR:
5849            set_UINT32BE(&cat_info.flFinderInfo.creator, values[i].i);
5850            break;
5851         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
5852            set_UINT16BE(&cat_info.flFinderInfo.flags, values[i].i);
5853            break;
5854         case IMGTOOLATTR_INT_MAC_COORDX:
5855            set_UINT16BE(&cat_info.flFinderInfo.location.h, values[i].i);
5856            break;
5857         case IMGTOOLATTR_INT_MAC_COORDY:
5858            set_UINT16BE(&cat_info.flFinderInfo.location.v, values[i].i);
5859            break;
5860         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
5861            set_UINT16BE(&cat_info.flFinderInfo.fldr, values[i].i);
5862            break;
5863         case IMGTOOLATTR_INT_MAC_ICONID:
5864            set_UINT16BE(&cat_info.flXFinderInfo.iconID, values[i].i);
5865            break;
5866         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
5867            cat_info.flXFinderInfo.script = values[i].i;
5868            break;
5869         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
5870            cat_info.flXFinderInfo.XFlags = values[i].i;
5871            break;
5872         case IMGTOOLATTR_INT_MAC_COMMENTID:
5873            set_UINT16BE(&cat_info.flXFinderInfo.comment, values[i].i);
5874            break;
5875         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
5876            set_UINT32BE(&cat_info.flXFinderInfo.putAway, values[i].i);
5877            break;
5878
5879         case IMGTOOLATTR_TIME_CREATED:
5880            cat_info.createDate = mac_setup_time(values[i].t);
5881            break;
5882         case IMGTOOLATTR_TIME_LASTMODIFIED:
5883            cat_info.modifyDate = mac_setup_time(values[i].t);
5884            break;
5885      }
5886   }
5887
5888   /* resolve path and fetch file info from directory/catalog */
5889   err = mac_lookup_path(image, path, &parID, filename, &cat_info, TRUE);
5890   if (err)
5891      return err;
5892
5893   return IMGTOOLERR_SUCCESS;
5894}
5895
5896
5897
5898/*************************************
5899 *
5900 *  Our very own resource manager
5901 *
5902 *************************************/
5903
5904static const void *mac_walk_resources(const void *resource_fork, size_t resource_fork_length,
5905   UINT32 resource_type,
5906   int (*discriminator)(const void *resource, UINT16 id, UINT32 length, void *param_),
5907   void *param, UINT16 *resource_id, UINT32 *resource_length)
5908{
5909   UINT32 resource_data_offset, resource_data_length;
5910   UINT32 resource_map_offset, resource_map_length;
5911   UINT32 resource_typelist_count, resource_typelist_offset;
5912   UINT32 resource_entry_offset, resource_entry_count;
5913   UINT32 i, this_resource_type;
5914   UINT32 this_resource_data, this_resource_length;
5915   UINT16 this_resource_id;
5916   const void *this_resource_ptr;
5917
5918   if (resource_fork_length < 16)
5919      return NULL;
5920
5921   /* read resource header; its ok if anything past this point fails */
5922   resource_data_offset = pick_integer_be(resource_fork,  0, 4);
5923   resource_map_offset  = pick_integer_be(resource_fork,  4, 4);
5924   resource_data_length = pick_integer_be(resource_fork,  8, 4);
5925   resource_map_length  = pick_integer_be(resource_fork, 12, 4);
5926   if ((resource_data_offset + resource_data_length) > resource_fork_length)
5927      return NULL;
5928   if ((resource_map_offset + resource_map_length) > resource_fork_length)
5929      return NULL;
5930   if (resource_map_length < 30)
5931      return NULL;
5932
5933   /* read resource map and locate the resource type list */
5934   resource_typelist_offset = pick_integer_be(resource_fork,
5935      resource_map_offset + 24, 2) + resource_map_offset;
5936   if ((resource_typelist_offset + 2) > resource_fork_length)
5937      return NULL;
5938   resource_typelist_count = pick_integer_be(resource_fork,
5939      resource_typelist_offset, 2) + 1;
5940   if ((resource_typelist_offset + resource_typelist_count * 16 + 2) > resource_fork_length)
5941      return NULL;
5942
5943   /* scan the resource type list and locate the entries for this type */
5944   resource_entry_count = 0;
5945   resource_entry_offset = 0;
5946   for (i = 0; i < resource_typelist_count; i++)
5947   {
5948      this_resource_type = pick_integer_be(resource_fork, resource_typelist_offset
5949         + (i * 8) + 2 + 0, 4);
5950      if (this_resource_type == resource_type)
5951      {
5952         resource_entry_count = pick_integer_be(resource_fork, resource_typelist_offset
5953            + (i * 8) + 2 + 4, 2) + 1;
5954         resource_entry_offset = pick_integer_be(resource_fork, resource_typelist_offset
5955            + (i * 8) + 2 + 6, 2) + resource_typelist_offset;
5956         break;
5957      }
5958   }
5959
5960   /* scan the resource entries, and find the correct resource */
5961   for (i = 0; i < resource_entry_count; i++)
5962   {
5963      this_resource_id = pick_integer_be(resource_fork, resource_entry_offset
5964         + (i * 12) + 0, 2);
5965      this_resource_data = pick_integer_be(resource_fork, resource_entry_offset
5966         + (i * 12) + 5, 3) + resource_data_offset;
5967      if ((this_resource_data + 4) > resource_fork_length)
5968         return NULL;
5969
5970      /* gauge the length */
5971      this_resource_length = pick_integer_be(resource_fork, this_resource_data, 4);
5972      this_resource_data += 4;
5973      if ((this_resource_data + this_resource_length) > resource_fork_length)
5974         return NULL;
5975
5976      this_resource_ptr = ((const UINT8 *) resource_fork) + this_resource_data;
5977      if (discriminator(this_resource_ptr, this_resource_id,
5978         this_resource_length, param))
5979      {
5980         if (resource_length)
5981            *resource_length = this_resource_length;
5982         if (resource_id)
5983            *resource_id = this_resource_id;
5984         return this_resource_ptr;
5985      }
5986   }
5987
5988   return NULL;
5989}
5990
5991
5992
5993static int get_resource_discriminator(const void *resource, UINT16 id, UINT32 length, void *param)
5994{
5995   const UINT16 *id_ptr = (const UINT16 *) param;
5996   return id == *id_ptr;
5997}
5998
5999
6000
6001static const void *mac_get_resource(const void *resource_fork, size_t resource_fork_length,
6002   UINT32 resource_type, UINT16 resource_id, UINT32 *resource_length)
6003{
6004   return mac_walk_resources(resource_fork, resource_fork_length,
6005      resource_type, get_resource_discriminator, &resource_id, NULL, resource_length);
6006}
6007
6008
6009
6010/*************************************
6011 *
6012 *  Custom icons
6013 *
6014 *************************************/
6015
6016static int bundle_discriminator(const void *resource, UINT16 id, UINT32 length, void *param)
6017{
6018   UINT32 this_creator_code = pick_integer_be(resource, 0, 4);
6019   UINT32 desired_creator_code = *((UINT32 *) param);
6020   return this_creator_code == desired_creator_code;
6021}
6022
6023
6024
6025static int get_pixel(const UINT8 *src, int width, int height, int bpp,
6026   int x, int y)
6027{
6028   UINT8 byte, mask;
6029   int bit_position;
6030
6031   byte = src[(y * width + x) * bpp / 8];
6032   bit_position = 8 - ((x % (8 / bpp)) + 1) * bpp;
6033   mask = (1 << bpp) - 1;
6034   return (byte >> bit_position) & mask;
6035}
6036
6037
6038
6039static int load_icon(UINT32 *dest, const void *resource_fork, UINT64 resource_fork_length,
6040   UINT32 resource_type, UINT16 resource_id, int width, int height, int bpp,
6041   const UINT32 *palette, int has_mask)
6042{
6043   int success = FALSE;
6044   int y, x, color, is_masked;
6045   UINT32 pixel;
6046   const UINT8 *src;
6047   UINT32 resource_length;
6048   UINT32 frame_length;
6049   UINT32 total_length;
6050
6051   frame_length = width * height * bpp / 8;
6052   total_length = frame_length * (has_mask ? 2 : 1);
6053
6054   /* attempt to fetch resource */
6055   src = mac_get_resource(resource_fork, resource_fork_length, resource_type,
6056      resource_id, &resource_length);
6057   if (src && (resource_length == total_length))
6058   {
6059      for (y = 0; y < height; y++)
6060      {
6061         for (x = 0; x < width; x ++)
6062         {
6063            /* first check mask bit */
6064            if (has_mask)
6065               is_masked = get_pixel(src + frame_length, width, height, bpp, x, y);
6066            else
6067               is_masked = dest[y * width + x] >= 0x80000000;
6068
6069            if (is_masked)
6070            {
6071               /* mask is ok; check the actual icon */
6072               color = get_pixel(src, width, height, bpp, x, y);
6073               pixel = palette[color] | 0xFF000000;
6074            }
6075            else
6076            {
6077               /* masked out; nothing */
6078               pixel = 0;
6079            }
6080
6081            dest[y * width + x] = pixel;
6082         }
6083      }
6084      success = TRUE;
6085   }
6086   return success;
6087}
6088
6089
6090
6091static imgtoolerr_t mac_image_geticoninfo(imgtool_partition *partition, const char *path, imgtool_iconinfo *iconinfo)
6092{
6093   static const UINT32 mac_palette_1bpp[2] = { 0xFFFFFF, 0x000000 };
6094
6095   static const UINT32 mac_palette_4bpp[16] =
6096   {
6097      0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5,
6098      0x0000D4, 0x02ABEA, 0x1FB714, 0x006411, 0x562C05, 0x90713A,
6099      0xC0C0C0, 0x808080, 0x404040, 0x000000
6100   };
6101
6102   static const UINT32 mac_palette_8bpp[256] =
6103   {
6104      0xFFFFFF, 0xFFFFCC, 0xFFFF99, 0xFFFF66, 0xFFFF33, 0xFFFF00,
6105      0xFFCCFF, 0xFFCCCC, 0xFFCC99, 0xFFCC66, 0xFFCC33, 0xFFCC00,
6106      0xFF99FF, 0xFF99CC, 0xFF9999, 0xFF9966, 0xFF9933, 0xFF9900,
6107      0xFF66FF, 0xFF66CC, 0xFF6699, 0xFF6666, 0xFF6633, 0xFF6600,
6108      0xFF33FF, 0xFF33CC, 0xFF3399, 0xFF3366, 0xFF3333, 0xFF3300,
6109      0xFF00FF, 0xFF00CC, 0xFF0099, 0xFF0066, 0xFF0033, 0xFF0000,
6110      0xCCFFFF, 0xCCFFCC, 0xCCFF99, 0xCCFF66, 0xCCFF33, 0xCCFF00,
6111      0xCCCCFF, 0xCCCCCC, 0xCCCC99, 0xCCCC66, 0xCCCC33, 0xCCCC00,
6112      0xCC99FF, 0xCC99CC, 0xCC9999, 0xCC9966, 0xCC9933, 0xCC9900,
6113      0xCC66FF, 0xCC66CC, 0xCC6699, 0xCC6666, 0xCC6633, 0xCC6600,
6114      0xCC33FF, 0xCC33CC, 0xCC3399, 0xCC3366, 0xCC3333, 0xCC3300,
6115      0xCC00FF, 0xCC00CC, 0xCC0099, 0xCC0066, 0xCC0033, 0xCC0000,
6116      0x99FFFF, 0x99FFCC, 0x99FF99, 0x99FF66, 0x99FF33, 0x99FF00,
6117      0x99CCFF, 0x99CCCC, 0x99CC99, 0x99CC66, 0x99CC33, 0x99CC00,
6118      0x9999FF, 0x9999CC, 0x999999, 0x999966, 0x999933, 0x999900,
6119      0x9966FF, 0x9966CC, 0x996699, 0x996666, 0x996633, 0x996600,
6120      0x9933FF, 0x9933CC, 0x993399, 0x993366, 0x993333, 0x993300,
6121      0x9900FF, 0x9900CC, 0x990099, 0x990066, 0x990033, 0x990000,
6122      0x66FFFF, 0x66FFCC, 0x66FF99, 0x66FF66, 0x66FF33, 0x66FF00,
6123      0x66CCFF, 0x66CCCC, 0x66CC99, 0x66CC66, 0x66CC33, 0x66CC00,
6124      0x6699FF, 0x6699CC, 0x669999, 0x669966, 0x669933, 0x669900,
6125      0x6666FF, 0x6666CC, 0x666699, 0x666666, 0x666633, 0x666600,
6126      0x6633FF, 0x6633CC, 0x663399, 0x663366, 0x663333, 0x663300,
6127      0x6600FF, 0x6600CC, 0x660099, 0x660066, 0x660033, 0x660000,
6128      0x33FFFF, 0x33FFCC, 0x33FF99, 0x33FF66, 0x33FF33, 0x33FF00,
6129      0x33CCFF, 0x33CCCC, 0x33CC99, 0x33CC66, 0x33CC33, 0x33CC00,
6130      0x3399FF, 0x3399CC, 0x339999, 0x339966, 0x339933, 0x339900,
6131      0x3366FF, 0x3366CC, 0x336699, 0x336666, 0x336633, 0x336600,
6132      0x3333FF, 0x3333CC, 0x333399, 0x333366, 0x333333, 0x333300,
6133      0x3300FF, 0x3300CC, 0x330099, 0x330066, 0x330033, 0x330000,
6134      0x00FFFF, 0x00FFCC, 0x00FF99, 0x00FF66, 0x00FF33, 0x00FF00,
6135      0x00CCFF, 0x00CCCC, 0x00CC99, 0x00CC66, 0x00CC33, 0x00CC00,
6136      0x0099FF, 0x0099CC, 0x009999, 0x009966, 0x009933, 0x009900,
6137      0x0066FF, 0x0066CC, 0x006699, 0x006666, 0x006633, 0x006600,
6138      0x0033FF, 0x0033CC, 0x003399, 0x003366, 0x003333, 0x003300,
6139      0x0000FF, 0x0000CC, 0x000099, 0x000066, 0x000033, 0xEE0000,
6140      0xDD0000, 0xBB0000, 0xAA0000, 0x880000, 0x770000, 0x550000,
6141      0x440000, 0x220000, 0x110000, 0x00EE00, 0x00DD00, 0x00BB00,
6142      0x00AA00, 0x008800, 0x007700, 0x005500, 0x004400, 0x002200,
6143      0x001100, 0x0000EE, 0x0000DD, 0x0000BB, 0x0000AA, 0x000088,
6144      0x000077, 0x000055, 0x000044, 0x000022, 0x000011, 0xEEEEEE,
6145      0xDDDDDD, 0xBBBBBB, 0xAAAAAA, 0x888888, 0x777777, 0x555555,
6146      0x444444, 0x222222, 0x111111, 0x000000
6147   };
6148
6149   static const UINT32 attrs[4] =
6150   {
6151      IMGTOOLATTR_INT_MAC_TYPE,
6152      IMGTOOLATTR_INT_MAC_CREATOR,
6153      IMGTOOLATTR_INT_MAC_FINDERFLAGS
6154   };
6155
6156   imgtoolerr_t err;
6157   imgtool_attribute attr_values[3];
6158   UINT32 type_code, creator_code, finder_flags;
6159   imgtool_stream *stream = NULL;
6160   const void *resource_fork;
6161   UINT64 resource_fork_length;
6162   const void *bundle;
6163   UINT32 bundle_length, pos, fref_pos, icn_pos, i;
6164   UINT16 local_id = 0, resource_id;
6165   UINT32 fref_bundleentry_length, icn_bundleentry_length;
6166   const void *fref;
6167   UINT32 resource_length;
6168
6169   assert((sizeof(attrs) / sizeof(attrs[0]) - 1)
6170      == (sizeof(attr_values) / sizeof(attr_values[0])));
6171
6172   /* first retrieve type and creator code */
6173   err = mac_image_getattrs(partition, path, attrs, attr_values);
6174   if (err)
6175      goto done;
6176   type_code = (UINT32) attr_values[0].i;
6177   creator_code = (UINT32) attr_values[1].i;
6178   finder_flags = (UINT32) attr_values[2].i;
6179
6180   /* check the bundle bit; if clear (and the type is not 'APPL'), use the
6181    * desktop file */
6182   if (!(finder_flags & 0x2000) && (type_code != /* APPL */ 0x4150504C))
6183      path = "Desktop\0";
6184
6185   stream = stream_open_mem(NULL, 0);
6186   if (!stream)
6187   {
6188      err = IMGTOOLERR_SUCCESS;
6189      goto done;
6190   }
6191
6192   /* read in the resource fork */
6193   err = mac_image_readfile(partition, path, "RESOURCE_FORK", stream);
6194   if (err)
6195      goto done;
6196   resource_fork = stream_getptr(stream);
6197   resource_fork_length = stream_size(stream);
6198
6199   /* attempt to look up the bundle */
6200   bundle = mac_walk_resources(resource_fork, resource_fork_length, /* BNDL */ 0x424E444C,
6201      bundle_discriminator, &creator_code, NULL, &bundle_length);
6202   if (!bundle)
6203      goto done;
6204
6205   /* find the FREF and the icon family */
6206   pos = 8;
6207   fref_pos = icn_pos = 0;
6208   fref_bundleentry_length = icn_bundleentry_length = 0;
6209   while((pos + 10) <= bundle_length)
6210   {
6211      UINT32 this_bundleentry_type = pick_integer_be(bundle, pos + 0, 4);
6212      UINT32 this_bundleentry_length = pick_integer_be(bundle, pos + 4, 2) + 1;
6213
6214      if (this_bundleentry_type == /* FREF */ 0x46524546)
6215      {
6216         fref_pos = pos;
6217         fref_bundleentry_length = this_bundleentry_length;
6218      }
6219      if (this_bundleentry_type == /* ICN# */ 0x49434E23)
6220      {
6221         icn_pos = pos;
6222         icn_bundleentry_length = this_bundleentry_length;
6223      }
6224      pos += 6 + this_bundleentry_length * 4;
6225   }
6226   if (!fref_pos || !icn_pos)
6227      goto done;
6228
6229   /* look up the FREF */
6230   for (i = 0; i < fref_bundleentry_length; i++)
6231   {
6232      local_id = pick_integer_be(bundle, fref_pos + (i * 4) + 6, 2);
6233      resource_id = pick_integer_be(bundle, fref_pos + (i * 4) + 8, 2);
6234
6235      fref = mac_get_resource(resource_fork, resource_fork_length,
6236         /* FREF */ 0x46524546, resource_id, &resource_length);
6237      if (fref && (resource_length >= 7))
6238      {
6239         if (pick_integer_be(fref, 0, 4) == type_code)
6240            break;
6241      }
6242   }
6243   if (i >= fref_bundleentry_length)
6244      goto done;
6245
6246   /* now look up the icon family */
6247   resource_id = 0;
6248   for (i = 0; i < icn_bundleentry_length; i++)
6249   {
6250      if (pick_integer_be(bundle, icn_pos + (i * 4) + 6, 2) == local_id)
6251      {
6252         resource_id = pick_integer_be(bundle, icn_pos + (i * 4) + 8, 2);
6253         break;
6254      }
6255   }
6256   if (i >= icn_bundleentry_length)
6257      goto done;
6258
6259   /* fetch 32x32 icons (ICN#, icl4, icl8) */
6260   if (load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6261      /* ICN# */ 0x49434E23, resource_id, 32, 32, 1, mac_palette_1bpp, TRUE))
6262   {
6263      iconinfo->icon32x32_specified = 1;
6264
6265      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6266         /* icl4 */ 0x69636C34, resource_id, 32, 32, 4, mac_palette_4bpp, FALSE);
6267      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6268         /* icl8 */ 0x69636C38, resource_id, 32, 32, 8, mac_palette_8bpp, FALSE);
6269   }
6270
6271   /* fetch 16x16 icons (ics#, ics4, ics8) */
6272   if (load_icon((UINT32 *) iconinfo->icon16x16, resource_fork, resource_fork_length,
6273      /* ics# */ 0x69637323, resource_id, 16, 16, 1, mac_palette_1bpp, TRUE))
6274   {
6275      iconinfo->icon16x16_specified = 1;
6276
6277      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6278         /* ics4 */ 0x69637334, resource_id, 32, 32, 4, mac_palette_4bpp, FALSE);
6279      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6280         /* ics8 */ 0x69637338, resource_id, 32, 32, 8, mac_palette_8bpp, FALSE);
6281   }
6282
6283done:
6284   if (stream)
6285      stream_close(stream);
6286   return err;
6287}
6288
6289
6290
6291/*************************************
6292 *
6293 *  File transfer suggestions
6294 *
6295 *************************************/
6296
6297static imgtoolerr_t mac_image_suggesttransfer(imgtool_partition *partition, const char *path, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
6298{
6299   imgtoolerr_t err;
6300   UINT32 parID;
6301   mac_str255 filename;
6302   mac_dirent cat_info;
6303   imgtool_image *img = imgtool_partition_image(partition);
6304   mac_l2_imgref *image = get_imgref(img);
6305   mac_filecategory_t file_category = MAC_FILECATEGORY_DATA;
6306
6307   if (path)
6308   {
6309      /* resolve path and fetch file info from directory/catalog */
6310      err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
6311      if (err)
6312         return err;
6313      if (cat_info.dataRecType != hcrt_File)
6314         return IMGTOOLERR_FILENOTFOUND;
6315
6316      file_category = (cat_info.rsrcLogicalSize > 0) ? MAC_FILECATEGORY_FORKED : MAC_FILECATEGORY_DATA;
6317   }
6318
6319   mac_suggest_transfer(file_category, suggestions, suggestions_length);
6320   return IMGTOOLERR_SUCCESS;
6321}
6322
6323
6324
6325/*************************************
6326 *
6327 *  Module population
6328 *
6329 *************************************/
6330
6331static void generic_mac_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
6332{
6333   switch(state)
6334   {
6335      /* --- the following bits of info are returned as 64-bit signed integers --- */
6336      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
6337      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(struct mac_l2_imgref); break;
6338      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(struct mac_iterator); break;
6339      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = ':'; break;
6340
6341      /* --- the following bits of info are returned as NULL-terminated strings --- */
6342      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
6343      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
6344
6345      /* --- the following bits of info are returned as pointers to data or functions --- */
6346      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
6347      case IMGTOOLINFO_PTR_CLOSE:                     /* info->close = mac_image_exit */; break;
6348      case IMGTOOLINFO_PTR_INFO:                     info->info = mac_image_info; break;
6349      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = mac_image_beginenum; break;
6350      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = mac_image_nextenum; break;
6351      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = mac_image_freespace; break;
6352      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = mac_image_readfile; break;
6353      case IMGTOOLINFO_PTR_LIST_FORKS:               info->list_forks = mac_image_listforks; break;
6354      case IMGTOOLINFO_PTR_GET_ATTRS:                  info->get_attrs = mac_image_getattrs; break;
6355      case IMGTOOLINFO_PTR_SET_ATTRS:                  info->set_attrs = mac_image_setattrs; break;
6356      case IMGTOOLINFO_PTR_GET_ICON_INFO:               info->get_iconinfo = mac_image_geticoninfo; break;
6357      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = mac_image_suggesttransfer; break;
6358      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_apple35_mac; break;
6359   }
6360}
6361
6362
6363
6364void mac_mfs_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
6365{
6366   switch(state)
6367   {
6368      /* --- the following bits of info are returned as NULL-terminated strings --- */
6369      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "mac_mfs"); break;
6370      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "Mac MFS Floppy"); break;
6371
6372      /* --- the following bits of info are returned as pointers to data or functions --- */
6373      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = mfs_image_create; break;
6374      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = mfs_image_open; break;
6375      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = mac_image_writefile; break;
6376
6377      default: generic_mac_get_info(imgclass, state, info); break;
6378   }
6379}
6380
6381
6382
6383void mac_hfs_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
6384{
6385   switch(state)
6386   {
6387      /* --- the following bits of info are returned as NULL-terminated strings --- */
6388      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "mac_hfs"); break;
6389      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "Mac HFS Floppy"); break;
6390
6391      /* --- the following bits of info are returned as pointers to data or functions --- */
6392      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = hfs_image_open; break;
6393
6394      default: generic_mac_get_info(imgclass, state, info); break;
6395   }
6396}
src/mess/tools/imgtool/vmsx_tap.c
r1339r1340
1/*
2    vMSX tap format
3
4    Virtual MSX 1.x (being replaced by the MSX driver in mess) had
5    it's on format for cassette recordings. The format is similar
6    to .cas files; however several recordings could be stored in
7    one file.
8
9    Virtual MSX was never really popular; I haven't seen any of these
10    files on the internet. However for completeness sake I've added
11    this converter. It's read only; the MSX driver cannot read
12    these files, but can read the .cas files (like most other MSX
13    emulators). Further use and specially distribution of the .tap files
14    is discouraged as Virtual MSX is obsolete (along with its private
15    file formats).
16
17    These files used the M$ mmio functions (similar to .aiff files). There
18    is an INFO block which lists all files in the archive. The TAPE block
19    contains the actual data.
20
21   Original code in Virtual MSX:
22
23      ftp://ftp.komkon.org/pub/EMUL8/MSX/Emulators/VMSX1SRC.zip
24   
25   It's in the file TAPE.C.
26
27   RIFF format specs:
28
29      http://www.saettler.com/RIFFMCI/riffmci.html
30
31
32    This module converts the files to .cas files. Implemented are:
33
34    dir - list all the files in the archive as "%title%-%type%.cas"
35    getall - writes all the files to disk
36    get - gets one file. If "getall" fails, due to characters in the
37          filename your FS/OS doesn't support, use:
38
39   imgtool get vmsx_tap monmsx.tap monmsx-binary.cas monmsx.cas
40
41    for example.
42
43   Sean Young
44*/
45
46#include "osdepend.h"
47#include "imgtoolx.h"
48#include "utils.h"
49
50typedef struct
51    {
52    char        title[32];
53    char        type[10];
54    char       chunk[4];
55    } TAP_ENTRY;
56
57typedef struct
58   {
59   imgtool_image       base;
60   imgtool_stream       *file_handle;
61   int       size;
62   UINT8      *data;
63   int       count;
64   TAP_ENTRY    *entries;
65   } TAP_IMAGE;
66
67typedef struct
68   {
69   imgtool_directory    base;
70   TAP_IMAGE   *image;
71   int         index;
72   } TAP_ITERATOR;
73
74static int vmsx_tap_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
75static void vmsx_tap_image_exit(imgtool_image *img);
76static int vmsx_tap_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
77static int vmsx_tap_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
78static void vmsx_tap_image_closeenum(imgtool_directory *enumeration);
79static int vmsx_tap_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
80
81IMAGEMODULE(
82   vmsx_tap,
83   "Virtual MSX Tape archive",      /* human readable name */
84   "tap",                        /* file extension */
85   NULL,                        /* crcfile */
86   NULL,                        /* crc system name */
87   NULL,                        /* eoln */
88   0,                           /* flags */
89   vmsx_tap_image_init,            /* init function */
90   vmsx_tap_image_exit,            /* exit function */
91   NULL,                        /* info function */
92   vmsx_tap_image_beginenum,         /* begin enumeration */
93   vmsx_tap_image_nextenum,         /* enumerate next */
94   vmsx_tap_image_closeenum,         /* close enumeration */
95   NULL,                        /* free space on image */
96   vmsx_tap_image_readfile,         /* read file */
97   NULL,/* write file */
98   NULL,/* delete file */
99   NULL,/* create image */
100   NULL,
101   NULL,
102   NULL,
103   NULL
104)
105
106static const UINT8 CasHeader[8] = { 0x1F,0xA6,0xDE,0xBA,0xCC,0x13,0x7D,0x74 };
107
108
109static int vmsx_tap_read_image (TAP_IMAGE *image)
110   {
111   unsigned char *p, *pmem;
112    unsigned int pos, i, size;
113   UINT32 offset;
114
115   pmem = image->data;
116    size = image->size;
117    pos = 0;
118    while ( (pos + 8) < size)
119      {
120      offset = *((UINT32*)(pmem + pos + 4));
121      offset = LITTLE_ENDIANIZE_INT32 (offset);
122      if (strncmp ((char*)pmem + pos, "INFO", 4) )
123         {
124         /* not this chunk, skip */
125         if (offset & 1) offset++; /* pad byte */
126         pos += offset + 8;
127         continue;
128         }
129      /* found it */
130      pos += 8;
131      p = pmem + pos;
132      /* intregity check */
133      if ( (offset + pos) > size)
134         return IMGTOOLERR_CORRUPTIMAGE;
135      if (p[0] != 0 || p[1] != 1)
136         return IMGTOOLERR_CORRUPTIMAGE;
137
138        image->count = p[2] + p[3] * 256;
139      p += 4;
140      if (offset < (image->count * (32 + 10 + 4) + 4) )
141         return IMGTOOLERR_CORRUPTIMAGE;
142
143      image->entries = (TAP_ENTRY*)malloc (
144         sizeof (TAP_ENTRY) * image->count);
145      if (!image->entries)
146         return IMGTOOLERR_OUTOFMEMORY;
147
148      for (i=0;i<image->count;i++)
149         {
150         /* this should really check the data */
151         strncpy (image->entries[i].title, (char*)p, 32); p += 32;
152         strncpy (image->entries[i].type, (char*)p, 10); p += 10;
153         memcpy (image->entries[i].chunk, (char*)p, 4); p += 4;
154         }
155
156      return 0;
157      }   
158
159   return IMGTOOLERR_MODULENOTFOUND;
160   }
161
162static int vmsx_tap_image_read_data (TAP_IMAGE *image, char *chunk, unsigned char **pcas, int *psize)
163   {
164   unsigned int caspos, pos = 0, found = 0, offset, size, tappos;
165   UINT32 tapblock;
166   unsigned char *p, *pmem;
167
168   size = image->size;
169   pmem = image->data;
170
171    while ( (pos + 8) < size)
172      {
173      offset = *((UINT32*)(pmem + pos + 4));
174      offset = LITTLE_ENDIANIZE_INT32 (offset);
175      if (memcmp (pmem + pos, "LIST", 4) )
176         {
177         if (offset & 1) offset++;
178         pos += offset + 8;
179         continue;
180         }
181
182      if (memcmp (pmem + pos + 8, "TAPE", 4) )
183         return IMGTOOLERR_CORRUPTIMAGE;
184
185      pos += 12;
186      offset -= 8;
187      if ( (pos + offset) > size)
188         return IMGTOOLERR_CORRUPTIMAGE;
189
190      pmem += pos;
191      size = offset;
192      found = 1;
193      break;
194      }
195
196    if (!found)
197      return IMGTOOLERR_CORRUPTIMAGE;
198
199   /* OK we've got the right data chunk. Now we can start looking for
200      the blocks */
201   pos = 0;
202   while ( (pos + 8) < size)
203      {
204      offset = *((UINT32*)(pmem + pos + 4));
205      offset = LITTLE_ENDIANIZE_INT32 (offset);
206      if (memcmp (pmem + pos, chunk, 4) )
207         {
208         if (offset & 1) offset++;
209         pos += offset + 8;
210         continue;
211         }
212
213      pos += 8;
214      caspos = tappos = 0;
215      p = malloc (offset * 2);
216      if (!p) return IMGTOOLERR_OUTOFMEMORY;
217
218      while ( (tappos + 4) <= offset)
219         {
220         tapblock = *((UINT32*)(pmem + pos + tappos));
221         tappos += 4;
222         tapblock = LITTLE_ENDIANIZE_INT32 (tapblock);
223         if (tapblock == 0xffffffff) break;
224         memcpy (p + caspos, CasHeader, 8);
225         caspos += 8;
226         memcpy (p + caspos, pmem + pos + tappos, tapblock);
227         caspos += tapblock;
228         tappos += tapblock;
229         }
230
231
232      *psize = caspos;
233      *pcas = p;
234   
235      return 0;
236      }
237
238   return IMGTOOLERR_CORRUPTIMAGE;
239   }
240
241static int vmsx_tap_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
242{
243   TAP_IMAGE *image;
244   int rc;
245
246   image = (TAP_IMAGE*)malloc (sizeof (TAP_IMAGE) );
247   if (!image) return IMGTOOLERR_OUTOFMEMORY;
248
249   *outimg = (imgtool_image*)image;
250
251   memset(image, 0, sizeof(TAP_IMAGE));
252   image->base.module = mod;
253   image->size=stream_size(f);
254   image->file_handle=f;
255
256   image->data = (UINT8*) malloc(image->size);
257   if (!image->data)
258   {
259      free(image);
260      *outimg=NULL;
261      return IMGTOOLERR_OUTOFMEMORY;
262   }
263
264   if (stream_read(f, image->data, image->size)!=image->size)
265   {
266      free(image);
267      *outimg=NULL;
268      return IMGTOOLERR_READERROR;
269   }
270
271   if ( (rc=vmsx_tap_read_image(image)) )   
272   {
273      if (image->entries) free(image->entries);
274      free(image);
275      *outimg=NULL;
276      return rc;
277   }
278
279   return 0;
280}
281
282static void vmsx_tap_image_exit(imgtool_image *img)
283{
284   TAP_IMAGE *image=(TAP_IMAGE*)img;
285   stream_close(image->file_handle);
286   free(image->entries);
287   free(image->data);
288   free(image);
289}
290
291static int vmsx_tap_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
292{
293   TAP_IMAGE *image=(TAP_IMAGE*)img;
294   TAP_ITERATOR *iter;
295
296   iter=*(TAP_ITERATOR**)outenum = (TAP_ITERATOR*) malloc(sizeof(TAP_ITERATOR));
297   if (!iter)
298      return IMGTOOLERR_OUTOFMEMORY;
299
300   iter->base.module = img->module;
301
302   iter->image=image;
303   iter->index = 0;
304   return 0;
305}
306
307static int vmsx_tap_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
308   {
309   TAP_ITERATOR *iter=(TAP_ITERATOR*)enumeration;
310   unsigned char *p;
311   int size, rc;
312   
313   ent->eof=iter->index>=iter->image->count;
314   if (!ent->eof)
315      {
316      sprintf (ent->fname, "%s-%s.cas",
317         iter->image->entries[iter->index].title,
318         iter->image->entries[iter->index].type);
319      size = 0;
320      p = NULL;
321      rc = vmsx_tap_image_read_data (iter->image,
322         iter->image->entries[iter->index].chunk, &p, &size);
323
324      ent->corrupt=rc;
325      if (!rc) ent->filesize = size;
326      iter->index++;
327
328      if (p) free (p);
329      }
330
331   return 0;
332   }
333
334static void vmsx_tap_image_closeenum(imgtool_directory *enumeration)
335   {
336   free (enumeration);
337   }
338
339static TAP_ENTRY* vmsx_tap_image_findfile(TAP_IMAGE *image, const char *fname)
340   {
341   int i;
342   char filename[64]; /* that's always enough! */
343
344   for (i=0; i<image->count; i++)
345      {
346      sprintf (filename, "%s-%s.cas",
347         image->entries[i].title, image->entries[i].type);
348      if (!strcmp(fname, filename) ) return image->entries+i;
349      }
350   return NULL;
351   }
352
353static int vmsx_tap_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
354   {
355   TAP_IMAGE *image=(TAP_IMAGE*)img;
356   TAP_ENTRY *entry;
357   unsigned char* p;
358   int size, rc;
359
360   if ((entry=vmsx_tap_image_findfile(image, fname))==NULL )
361      return IMGTOOLERR_MODULENOTFOUND;
362
363   rc = vmsx_tap_image_read_data (image, entry->chunk, &p, &size);
364   if (!rc)
365      {
366      if (stream_write(destf, p, size)!=size)
367         {
368         free (p);
369         return IMGTOOLERR_WRITEERROR;
370         }
371      }
372
373    free (p);
374
375   return rc;
376   }
377
src/mess/tools/imgtool/d64.h
r1339r1340
1void d64_open_helper (void);
2int cbm_compareNames (const unsigned char *left, const unsigned char *right);
3
src/mess/tools/imgtool/vmsx_gm2.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6
7/*
8   vMSX gmaster2.ram
9
10   Virtual MSX 1.x (being replaced by the MSX driver in mess) had
11   it's on format for Konami's Game Master 2 SRAM. The file was
12   always saved as gmaster2.ram; however the file was 16kB when
13   the actual data is 8kB. 8kB is redundant, which is not used
14   by MESS, Virtual MSX 2.0 (never finished), and the patches for
15   fMSX written by me (Sean Young). So suppose you'd like to use
16   the SRAM from Virtual MSX, use this very simple converter.
17
18*/
19
20#define NewName "gmaster2.mem"
21
22typedef struct {
23   imgtool_image         base;
24   imgtool_stream          *file_handle;
25   int          size;
26   unsigned char   *data;
27   int          count;
28   } GM2_IMAGE;
29
30typedef struct
31   {
32   imgtool_directory    base;
33   GM2_IMAGE   *image;
34   int         index;
35   } TAP_ITERATOR;
36
37static int vmsx_gm2_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
38static void vmsx_gm2_image_exit(imgtool_image *img);
39//static void vmsx_gm2_image_info(imgtool_image *img, char *string, const int len);
40static int vmsx_gm2_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
41static int vmsx_gm2_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
42static void vmsx_gm2_image_closeenum(imgtool_directory *enumeration);
43static int vmsx_gm2_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
44
45IMAGEMODULE(
46   vmsx_gm2,
47   "Virtual MSX Game Master 2 SRAM",      /* human readable name */
48   "ram",                        /* file extension */
49   NULL,                        /* crcfile */
50   NULL,                        /* crc system name */
51   NULL,                        /* eoln */
52   0,                           /* flags */
53   vmsx_gm2_image_init,            /* init function */
54   vmsx_gm2_image_exit,            /* exit function */
55   NULL,                        /* info function */
56   vmsx_gm2_image_beginenum,         /* begin enumeration */
57   vmsx_gm2_image_nextenum,         /* enumerate next */
58   vmsx_gm2_image_closeenum,         /* close enumeration */
59   NULL,                        /* free space on image */
60   vmsx_gm2_image_readfile,         /* read file */
61   NULL,/* write file */
62   NULL,/* delete file */
63   NULL,/* create image */
64   NULL,                        /* read sector */
65   NULL,                        /* write sector */
66   NULL,               /* file options */
67   NULL               /* create options */
68)
69
70static int vmsx_gm2_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
71{
72   GM2_IMAGE *image;
73
74   image = (GM2_IMAGE*)malloc (sizeof (GM2_IMAGE) );
75   if (!image) return IMGTOOLERR_OUTOFMEMORY;
76
77   *outimg = (imgtool_image*)image;
78
79   memset(image, 0, sizeof(GM2_IMAGE));
80   image->base.module = mod;
81   image->size=stream_size(f);
82   image->file_handle=f;
83
84    if (image->size != 0x4000)
85   {
86      free (image);
87      return IMGTOOLERR_READERROR;
88   }
89
90   image->data = (unsigned char *) malloc(image->size);
91   if ( (!image->data)
92       ||(stream_read(f, image->data, image->size)!=image->size) )
93   {
94      free(image);
95      *outimg=NULL;
96      return IMGTOOLERR_OUTOFMEMORY;
97   }
98
99   return 0;
100}
101
102static void vmsx_gm2_image_exit(imgtool_image *img)
103   {
104   GM2_IMAGE *image=(GM2_IMAGE*)img;
105   stream_close(image->file_handle);
106   free(image->data);
107   free(image);
108   }
109
110static int vmsx_gm2_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
111   {
112   GM2_IMAGE *image=(GM2_IMAGE*)img;
113   TAP_ITERATOR *iter;
114
115   iter=*(TAP_ITERATOR**)outenum = (TAP_ITERATOR*) malloc(sizeof(TAP_ITERATOR));
116   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
117
118   iter->base.module = img->module;
119
120   iter->image=image;
121   iter->index = 0;
122   return 0;
123   }
124
125static int vmsx_gm2_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
126   {
127   TAP_ITERATOR *iter=(TAP_ITERATOR*)enumeration;
128
129   ent->eof=iter->index;
130   if (!ent->eof)
131      {
132      strcpy (ent->fname, NewName);
133      ent->corrupt=0;
134      ent->filesize = 0x2000;
135      iter->index++;
136      }
137
138   return 0;
139   }
140
141static void vmsx_gm2_image_closeenum(imgtool_directory *enumeration)
142   {
143   free(enumeration);
144   }
145
146static int vmsx_gm2_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
147   {
148   GM2_IMAGE *image=(GM2_IMAGE*)img;
149
150   if (mame_stricmp (fname, NewName) )
151      return IMGTOOLERR_MODULENOTFOUND;
152
153   if (stream_write(destf, image->data + 0x1000, 0x1000)!=0x1000)
154         return IMGTOOLERR_WRITEERROR;
155
156   if (stream_write(destf, image->data + 0x3000, 0x1000)!=0x1000)
157         return IMGTOOLERR_WRITEERROR;
158
159   return 0;
160   }
161
src/mess/tools/imgtool/macutil.h
r1339r1340
1/****************************************************************************
2
3   macutil.h
4
5   Imgtool Utility code for manipulating certain Apple/Mac data structures
6   and conventions
7
8*****************************************************************************/
9
10#ifndef MACUTIL_H
11#define MACUTIL_H
12
13#include "imgtool.h"
14
15typedef enum
16{
17   MAC_FORK_DATA,
18   MAC_FORK_RESOURCE
19} mac_fork_t;
20
21typedef enum
22{
23   MAC_FILECATEGORY_DATA,
24   MAC_FILECATEGORY_TEXT,
25   MAC_FILECATEGORY_FORKED
26} mac_filecategory_t;
27
28
29/* converting Classic Mac OS time <==> Imgtool time */
30time_t mac_crack_time(UINT32 t);
31UINT32 mac_setup_time(time_t t);
32UINT32 mac_time_now(void);
33
34imgtoolerr_t mac_identify_fork(const char *fork_string, mac_fork_t *fork_num);
35
36void mac_suggest_transfer(mac_filecategory_t file_category, imgtool_transfer_suggestion *suggestions, size_t suggestions_length);
37
38void pascal_from_c_string(unsigned char *pstring, size_t pstring_len, const char *cstring);
39
40#endif /* MACUTIL_H */
src/mess/tools/imgtool/vzdos.c
r1339r1340
1/****************************************************************************
2
3   vzdos.c
4
5   Laser/VZ disk images
6
7****************************************************************************/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <math.h>
13#include "osdepend.h"
14#include "imgtool.h"
15#include "imgtoolx.h"
16#include "utils.h"
17#include "formats/vt_dsk.h"
18#include "iflopimg.h"
19
20/*
21
22sector format
23
24| GAP1 | IDAM | GAP2 | DATA | CHECKSUM | ...
25
26GAP1     = 80 80 80 80 80 00                                         6
27IDAM     = FE E7 18 C3 Track# Sector# Checksum-8 of prev. 2 bytes    7
28GAP2     = 80 80 80 80 80 80 00 C3 18 E7 FE                         11
29DATA     = 126 bytes actual data                                   126
30         = nextTrack# nextSector#                                    2
31CHECKSUM = Checksum-16 of the previous 128 bytes                     2
32                                                                   ---
33                                                                   154 bytes
34
35sectors 0 to 14 are used for the disk directory. sector 15 is used
36as track map, with one bit for each sector used.
37
38*/
39
40#define DATA_SIZE   (126)
41#define SECTOR_SIZE   (0x9a)
42#define MAX_DIRENTS   (15*8)
43
44/* vzdos directry entry */
45typedef struct vzdos_dirent
46{
47   char ftype;
48   char delimitor;
49   char fname[8];
50   UINT8 start_track;
51   UINT8 start_sector;
52   UINT16 start_address;
53   UINT16 end_address;
54} vzdos_dirent;
55
56typedef struct vz_iterator
57{
58   int index;
59   int eof;
60} vz_iterator;
61
62static const UINT8 sector_order[] =
63{
64   0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13
65};
66
67/*********************************************************************
68   Internal functions
69*********************************************************************/
70
71/* get length of filename without trailing spaces */
72static int vzdos_get_fname_len(const char *fname)
73{
74   int len;
75
76   for (len = 7; len > 0; len--)         
77      if (fname[len] != 0x20)
78         break;
79   
80   return len;   
81}
82
83/* calculate checksum-16 of buffer */
84static UINT16 chksum16(UINT8 *buffer, int len)
85{
86   int i;
87   UINT16 sum = 0;
88   
89   for (i = 0; i < len; i++)
90      sum += buffer[i];   
91   
92   return sum;
93}
94
95/* returns the offset where the actual sector data starts */
96static imgtoolerr_t vzdos_get_data_start(imgtool_image *img, int track, int sector, int *start)
97{
98   imgtoolerr_t ret;
99   UINT8 buffer[25]; /* enough to read the sector header */
100
101   ret = floppy_read_sector(imgtool_floppy(img), 0, track, sector_order[sector], 0, &buffer, sizeof(buffer));
102   if (ret) return ret;
103     
104   /* search for start of data */
105   if (memcmp(buffer + 19, "\xC3\x18\xE7\xFE", 4) == 0)
106      *start = 23;
107   else if (memcmp(buffer + 20, "\xC3\x18\xE7\xFE", 4) == 0)
108      *start = 24;
109   else if (memcmp(buffer + 21, "\xC3\x18\xE7\xFE", 4) == 0)
110      *start = 25;
111   else
112      return IMGTOOLERR_CORRUPTIMAGE;
113
114   return IMGTOOLERR_SUCCESS;
115}
116
117/* return the actual data of a sector */
118static imgtoolerr_t vzdos_read_sector_data(imgtool_image *img, int track, int sector, UINT8 *data)
119{
120   int ret, data_start;
121   UINT8 buffer[DATA_SIZE + 4]; /* data + checksum */
122
123   ret = vzdos_get_data_start(img, track, sector, &data_start);
124   if (ret) return ret;
125
126   ret = floppy_read_sector(imgtool_floppy(img), 0, track, sector_order[sector], data_start, &buffer, sizeof(buffer));
127   if (ret) return ret;
128
129   /* verify sector checksums */
130   if (pick_integer_le(buffer, DATA_SIZE + 2, 2) != chksum16(buffer, DATA_SIZE + 2))
131      return IMGTOOLERR_CORRUPTFILE;
132
133   memcpy(data, &buffer, DATA_SIZE + 2);
134   
135   return IMGTOOLERR_SUCCESS;
136}
137
138/* write data to sector */
139static imgtoolerr_t vzdos_write_sector_data(imgtool_image *img, int track, int sector, UINT8 *data)
140{
141   int ret, data_start;
142   UINT8 buffer[DATA_SIZE + 4]; /* data + checksum */
143
144   ret = vzdos_get_data_start(img, track, sector, &data_start);
145   if (ret) return ret;
146
147   memcpy(buffer, data, DATA_SIZE + 2);
148   place_integer_le(buffer, DATA_SIZE + 2, 2, chksum16(data, DATA_SIZE + 2));
149   
150   ret = floppy_write_sector(imgtool_floppy(img), 0, track, sector_order[sector], data_start, buffer, sizeof(buffer));
151   if (ret) return ret;
152   
153   return IMGTOOLERR_SUCCESS;
154}
155
156/* write formatted empty sector */
157static imgtoolerr_t vzdos_clear_sector(imgtool_image *img, int track, int sector)
158{
159   UINT8 data[DATA_SIZE + 2];
160   
161   memset(data, 0x00, sizeof(data));
162   
163   return vzdos_write_sector_data(img, track, sector, data);   
164}
165
166/* return a directory entry for an index */
167static imgtoolerr_t vzdos_get_dirent(imgtool_image *img, int index, vzdos_dirent *ent)
168{
169   int ret, entry;
170   UINT8 buffer[DATA_SIZE + 2];
171
172   ret = vzdos_read_sector_data(img, 0, (int) index / 8, buffer);
173   if (ret) return ret;
174   
175   entry = ((index % 8) * sizeof(vzdos_dirent));
176
177   memcpy(ent, &buffer[entry], 10);
178   ent->start_track   = pick_integer_le(&buffer[entry], 10, 1);
179   ent->start_sector  = pick_integer_le(&buffer[entry], 11, 1);
180   ent->start_address = pick_integer_le(&buffer[entry], 12, 2);
181   ent->end_address   = pick_integer_le(&buffer[entry], 14, 2);
182
183   if (ent->ftype == 0x00)
184      return IMGTOOLERR_FILENOTFOUND;
185
186   /* check values */
187   if (ent->start_track > 39)
188      return IMGTOOLERR_CORRUPTIMAGE;
189     
190   if (ent->start_sector > 15)
191      return IMGTOOLERR_CORRUPTIMAGE;
192
193   return IMGTOOLERR_SUCCESS;
194}
195
196/* save a directory entry to disk */
197static imgtoolerr_t vzdos_set_dirent(imgtool_image *img, int index, vzdos_dirent ent)
198{
199   int ret, entry;
200   UINT8 buffer[DATA_SIZE + 2];
201
202   /* read current sector with entries */
203   ret = vzdos_read_sector_data(img, 0, (int) index / 8, buffer);
204   if (ret) return ret;
205
206   entry = ((index % 8) * sizeof(vzdos_dirent));
207
208   memcpy(&buffer[entry], &ent, 10);
209   place_integer_le(buffer, entry + 10, 1, ent.start_track);
210   place_integer_le(buffer, entry + 11, 1, ent.start_sector);
211   place_integer_le(buffer, entry + 12, 2, ent.start_address);
212   place_integer_le(buffer, entry + 14, 2, ent.end_address);
213   
214   /* save new sector */
215   ret = vzdos_write_sector_data(img, 0, (int) index / 8, buffer);
216   if (ret) return ret;
217   
218   return IMGTOOLERR_SUCCESS;   
219}
220
221/* clear a directory entry */
222static imgtoolerr_t vzdos_clear_dirent(imgtool_image *img, int index)
223{
224   int ret;
225   vzdos_dirent entry;
226
227   memset(&entry, 0x00, sizeof(vzdos_dirent));
228
229   ret = vzdos_set_dirent(img, index, entry);
230   if (ret) return ret;
231     
232   return IMGTOOLERR_SUCCESS;
233}
234
235/* search the index for a directory entry */
236static imgtoolerr_t vzdos_searchentry(imgtool_image *image, const char *fname, int *entry) {
237   int i, len, ret;
238   vzdos_dirent ent;
239   char filename[9];
240
241   /* check for invalid filenames */
242   if (strlen(fname) > 8)
243      return IMGTOOLERR_BADFILENAME;
244     
245   /* TODO: check for invalid characters */
246   
247   *entry = -1;
248     
249   for (i = 0; i < MAX_DIRENTS; i++) {
250
251      ret = vzdos_get_dirent(image, i, &ent);
252      if (ret) return ret;
253     
254      len = vzdos_get_fname_len(ent.fname) + 1;
255
256      if (strlen(fname) != len)
257         continue;
258     
259      memset(filename, 0x00, sizeof(filename));
260      memcpy(filename, ent.fname, len);
261
262      if (!mame_stricmp(fname, filename)) {
263         *entry = i;
264         break;
265      }
266     
267   }
268   
269   if (*entry == -1)
270      return IMGTOOLERR_FILENOTFOUND;
271
272   return IMGTOOLERR_SUCCESS;
273}
274
275/* return a directory entry for a filename */
276static imgtoolerr_t vzdos_get_dirent_fname(imgtool_image *img, const char *fname, vzdos_dirent *ent)
277{
278   int ret, index;
279
280   ret = vzdos_searchentry(img, fname, &index);
281   if (ret) return ret;
282   
283   ret = vzdos_get_dirent(img, index, ent);
284   if (ret) return ret;   
285   
286   return IMGTOOLERR_SUCCESS;
287}
288
289static imgtoolerr_t vzdos_toggle_trackmap(imgtool_image *img, int track, int sector, int clear)
290{
291   int ret, value, bit;
292   UINT8 buffer[DATA_SIZE + 2];
293
294   /* get trackmap from image */
295   ret = vzdos_read_sector_data(img, 0, 15, buffer);
296   if (ret) return ret;
297
298   value = (int) (floor((track * 16 + sector) / 8) - 1);
299   bit   = 0x01 << ((track * 16 + sector) % 8);
300
301   if (clear)
302      buffer[value-1] &= ~bit;
303   else
304      buffer[value-1] |= bit;
305
306   ret = vzdos_write_sector_data(img, 0, 15, buffer);
307   if (ret) return ret;
308     
309   return IMGTOOLERR_SUCCESS;
310}
311
312/* clear a trackmap entry */
313static imgtoolerr_t vzdos_clear_trackmap(imgtool_image *img, int track, int sector)
314{
315   return vzdos_toggle_trackmap(img, track, sector, 1);
316}
317
318/* enable a trackmap entry */
319static imgtoolerr_t vzdos_set_trackmap(imgtool_image *img, int track, int sector)
320{
321   return vzdos_toggle_trackmap(img, track, sector, 0);
322}
323
324/* return the status of a trackmap entry */
325static imgtoolerr_t vzdos_get_trackmap(imgtool_image *img, int track, int sector, int *used)
326{
327   int ret, value, bit;
328   UINT8 buffer[DATA_SIZE + 2];
329
330   /* get trackmap from image */
331   ret = vzdos_read_sector_data(img, 0, 15, buffer);
332   if (ret) return ret;
333
334   value = (int) (floor((track * 16 + sector) / 8) - 1);
335   bit   = 0x01 << ((track * 16 + sector) % 8);
336
337   if (buffer[value-1] & bit)
338      *used = 1;
339   else
340      *used = 0;
341
342   return IMGTOOLERR_SUCCESS;   
343}
344
345/* return the next free sector */
346static imgtoolerr_t vzdos_free_trackmap(imgtool_image *img, int *track, int *sector)
347{
348   int ret, used = 0;
349   
350   for (*track = 1; *track < 40; (*track)++) {
351      for (*sector = 0; *sector < 16; (*sector)++) {
352         ret = vzdos_get_trackmap(img, *track, *sector, &used);
353         if (ret) return ret;
354         if (!used) return IMGTOOLERR_SUCCESS;
355      }   
356   }
357   
358   return IMGTOOLERR_NOSPACE;
359}
360
361static imgtoolerr_t vzdos_write_formatted_sector(imgtool_image *img, int track, int sector)
362{
363   int ret;
364   UINT8 sector_data[DATA_SIZE + 4];
365
366   UINT8 sector_header[24] = {
367      0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0xFE, 0xE7,
368      0x18, 0xC3, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80,
369      0x80, 0x80, 0x80, 0x00, 0xC3, 0x18, 0xE7, 0xFE
370   };
371   
372   memset(sector_data, 0x00, sizeof(sector_data));
373
374   sector_header[10] = (UINT8) track;         /* current track */
375   sector_header[11] = (UINT8) sector;         /* current sector */
376   sector_header[12] = (UINT8) track + sector;   /* checksum-8 */
377
378   ret = floppy_write_sector(imgtool_floppy(img), 0, track, sector_order[sector], 0, sector_header, sizeof(sector_header));
379   if (ret) return ret;
380
381   ret = floppy_write_sector(imgtool_floppy(img), 0, track, sector_order[sector], sizeof(sector_header), sector_data, sizeof(sector_data));
382   if (ret) return ret;
383
384   return IMGTOOLERR_SUCCESS;
385}
386
387/*********************************************************************
388   Imgtool module code
389*********************************************************************/
390
391static imgtoolerr_t vzdos_diskimage_beginenum(imgtool_directory *enumeration, const char *path)
392{
393   vz_iterator *iter;
394
395   iter = (vz_iterator *) imgtool_directory_extrabytes(enumeration);
396   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
397
398   iter->index = 1;
399   iter->eof = 0;
400
401   return IMGTOOLERR_SUCCESS;
402}
403
404static imgtoolerr_t vzdos_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
405{
406   vz_iterator *iter = (vz_iterator *) imgtool_directory_extrabytes(enumeration);
407
408   if (iter->eof == 1 || iter->index > MAX_DIRENTS) {
409   
410      ent->eof = 1;
411   
412   } else {
413     
414      const char *type;
415      int ret, len;
416      vzdos_dirent dirent;
417
418      ret = vzdos_get_dirent(imgtool_directory_image(enumeration), iter->index - 1, &dirent);
419     
420      if (dirent.ftype == 0x00) {
421         iter->eof = 1;
422         ent->eof = 1;
423         return IMGTOOLERR_SUCCESS;
424      }
425     
426      /* kill trailing spaces */
427      for (len = 7; len > 0; len--) {         
428         if (dirent.fname[len] != 0x20) {
429            break;
430         }
431      }
432     
433      memcpy(ent->filename, &dirent.fname, len + 1);
434      ent->filesize = dirent.end_address - dirent.start_address;
435     
436      switch (dirent.ftype) {
437         case 'T': type = "Basic";      break;
438         case 'B': type = "Binary";     break;
439         case 'D': type = "Data";       break;
440         case 'F': type = "Quickwrite"; break;
441         case 'A': type = "Assembler";  break;
442         case 'S': type = "Diskops";    break;
443         case 'W': type = "Wordpro";    break;
444         default: type = "Unknown";
445      }
446      snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%s", type);
447     
448      iter->index++;   
449   }
450   
451   return IMGTOOLERR_SUCCESS;
452}
453
454/* TRK 0 sector 15 is used to hold the track map of the disk with one bit
455   corresponding to a sector used. */
456static imgtoolerr_t vzdos_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
457{
458   imgtoolerr_t ret;
459   int i;
460   imgtool_image *image = imgtool_partition_image(partition);
461   UINT8 c, v, buffer[DATA_SIZE + 2];
462   *size = 0;
463
464   ret = vzdos_read_sector_data(image, 0, 15, buffer);
465   if (ret) return ret;
466
467   for (i = 0; i < DATA_SIZE; i++) {
468      v = buffer[i];
469      for (c = 0; v; c++) {
470         v &= v - 1;
471      }
472      *size += c * DATA_SIZE;
473   }
474   *size = (DATA_SIZE * 16 * 39) - *size;
475
476   return IMGTOOLERR_SUCCESS;
477}
478
479static imgtoolerr_t vzdos_diskimage_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
480{
481   imgtoolerr_t ret;
482   imgtool_image *image = imgtool_partition_image(partition);
483   int filesize, track, sector;
484   vzdos_dirent ent;
485   UINT8 buffer[DATA_SIZE + 2];
486     
487   ret = vzdos_get_dirent_fname(image, filename, &ent);
488   if (ret) return ret;
489   
490   filesize = ent.end_address - ent.start_address;
491   track = ent.start_track;
492   sector = ent.start_sector;
493
494   while (filesize > 0) {
495      int towrite;
496
497      ret = vzdos_read_sector_data(image, track, sector, buffer);
498      if (ret) return ret;
499
500      /* detect sectors pointing to themselfs */
501      if ((track == pick_integer_le(buffer, DATA_SIZE, 1)) && (sector == pick_integer_le(buffer, DATA_SIZE + 1, 1)))
502         return IMGTOOLERR_CORRUPTIMAGE;
503
504      /* load next track and sector values */               
505      track  = pick_integer_le(buffer, DATA_SIZE, 1);
506      sector = pick_integer_le(buffer, DATA_SIZE + 1, 1);
507     
508      /* track 0 is invalid */
509      if ((track == 0) && (filesize > DATA_SIZE))
510         return IMGTOOLERR_CORRUPTIMAGE;
511     
512      /* write either DATA_SIZE or the remaining bytes */
513      towrite = filesize > DATA_SIZE ? DATA_SIZE : filesize;
514     
515      if (stream_write(destf, buffer, towrite) != towrite)
516         return IMGTOOLERR_WRITEERROR;
517
518      filesize -= DATA_SIZE;
519   }
520     
521   return IMGTOOLERR_SUCCESS;
522}
523
524/* deletes directory entry, clears trackmap entries and sectors */
525static imgtoolerr_t vzdos_diskimage_deletefile(imgtool_partition *partition, const char *fname)
526{
527   imgtoolerr_t ret;
528   imgtool_image *img = imgtool_partition_image(partition);
529   int index, filesize, track, sector, next_track, next_sector;
530   vzdos_dirent entry, next_entry;
531   UINT8 buffer[DATA_SIZE + 2];
532
533   ret = vzdos_get_dirent_fname(img, fname, &entry);
534   if (ret) return ret;
535
536   ret = floppy_read_sector(imgtool_floppy(img), 0, entry.start_track, sector_order[entry.start_sector], 24, &buffer, DATA_SIZE + 2);
537   if (ret) return ret;
538
539   filesize = entry.end_address - entry.start_address;
540   track    = entry.start_track;
541   sector   = entry.start_sector;
542
543   /* delete directory entry */
544   ret = vzdos_searchentry(img, fname, &index);
545   if (ret) return ret;
546
547   ret = vzdos_get_dirent(img, index + 1, &next_entry);
548
549   if (ret == IMGTOOLERR_FILENOTFOUND) {
550
551      /* we are the last directory entry, just delete it */
552      ret = vzdos_clear_dirent(img, index);
553      if (ret) return ret;
554
555   } else if (ret) {
556
557      /* an error occured */
558      return ret;
559
560   } else {
561
562      ret = vzdos_set_dirent(img, index++, next_entry);
563      if (ret) return ret;
564
565      while ((ret = vzdos_get_dirent(img, index + 1, &next_entry)) != IMGTOOLERR_FILENOTFOUND) {
566         if (ret) return ret;
567         ret = vzdos_set_dirent(img, index++, next_entry);
568         if (ret) return ret;
569      }
570
571      ret = vzdos_clear_dirent(img, index);
572      if (ret) return ret;
573     
574   }
575   
576   /* clear sectors and trackmap entries */
577   while (filesize > 0) {
578   
579      filesize -= DATA_SIZE;
580   
581      /* clear trackmap entry */
582      ret = vzdos_clear_trackmap(img, track, sector);
583      if (ret) return ret;
584
585      /* load next track and sector values */               
586      next_track  = pick_integer_le(buffer, DATA_SIZE, 1);
587      next_sector = pick_integer_le(buffer, DATA_SIZE + 1, 1);
588     
589      /* overwrite sector with default values */
590      ret = vzdos_clear_sector(img, track, sector);
591      if (ret) return ret;
592
593      /* read next sector */
594      track  = next_track;
595      sector = next_sector;
596
597      if (filesize > 0) {
598         ret = floppy_read_sector(imgtool_floppy(img), 0, track, sector_order[sector], 24, &buffer, DATA_SIZE + 2);
599         if (ret) return ret;
600      }     
601           
602   }
603   
604   return IMGTOOLERR_SUCCESS;
605}
606
607static imgtoolerr_t vzdos_writefile(imgtool_partition *partition, int offset, imgtool_stream *sourcef, vzdos_dirent *entry)
608{
609   imgtoolerr_t ret;
610   imgtool_image *img = imgtool_partition_image(partition);
611   int index, track, sector, toread, next_track, next_sector;
612   vzdos_dirent temp_entry;
613   UINT64 filesize = 0, freespace = 0;
614   UINT8 buffer[DATA_SIZE + 2];
615   char filename[9];
616
617   /* is the image writeable? */
618   if (floppy_is_read_only(imgtool_floppy(img)))
619      return IMGTOOLERR_READONLY;
620
621   /* check for already existing filename -> overwrite */
622   strcpy(filename, entry->fname);
623   filename[vzdos_get_fname_len(entry->fname) + 1] = 0x00;
624   ret = vzdos_get_dirent_fname(img, filename, &temp_entry);
625   if (!ret) {
626      /* file already exists, delete it */
627      ret = vzdos_diskimage_deletefile(partition, filename);
628      if (ret) return ret;
629   } else if (ret != IMGTOOLERR_FILENOTFOUND) {
630      /* another error occured, return it */
631      return ret;
632   }
633   
634   ret = stream_seek(sourcef, offset, SEEK_SET);
635   if (ret) return ret;
636
637   /* check if there is enough space */
638   filesize = stream_size(sourcef) - offset;
639
640   ret = vzdos_diskimage_freespace(partition, &freespace);
641   if (ret) return ret;
642
643   if (filesize > freespace)
644      return IMGTOOLERR_NOSPACE;
645   
646   /* get next free track and sector */
647   ret = vzdos_free_trackmap(img, &track, &sector);
648   if (ret) return ret;
649
650   entry->end_address = entry->start_address + (unsigned int) filesize;
651   entry->start_track   = track;
652   entry->start_sector  = sector;
653
654   /* search for next free directory entry */
655   for (index = 0; index < MAX_DIRENTS; index++) {
656      ret = vzdos_get_dirent(img, index, &temp_entry);
657      if (ret == IMGTOOLERR_FILENOTFOUND)
658         break;
659      else if (ret)
660         return (ret);
661   }
662
663   /* write directory entry to disk */
664   ret = vzdos_set_dirent(img, index, *entry);
665   if (ret) return ret;
666
667   next_track  = 0;
668   next_sector = 0;
669   
670   /* write data to disk */
671   while (filesize > 0) {
672   
673      toread = filesize > DATA_SIZE ? DATA_SIZE : filesize;
674      stream_read(sourcef, buffer, toread);
675
676      filesize -= toread;   
677
678      /* mark sector as used */
679      ret = vzdos_set_trackmap(img, track, sector);
680      if (ret) return ret;
681
682      /* get track and sector for next sector */
683      if (filesize > 0) {   
684         ret = vzdos_free_trackmap(img, &next_track, &next_sector);
685         if (ret) return ret;
686      } else {
687         next_track = 0;
688         next_sector = 0;
689      }
690      buffer[DATA_SIZE]     = next_track;
691      buffer[DATA_SIZE + 1] = next_sector;
692
693      /* write sector to disk */
694      ret = vzdos_write_sector_data(img, track, sector, buffer);
695      if (ret) return ret;
696
697      track  = next_track;
698      sector = next_sector;
699   }
700     
701   return IMGTOOLERR_SUCCESS;
702   
703}
704
705/* create a new file or overwrite a file */
706static imgtoolerr_t vzdos_diskimage_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
707{
708   imgtoolerr_t ret;
709   int ftype;
710   vzdos_dirent entry;
711
712   /* TODO: check for leading spaces and strip */
713   if (strlen(filename) > 8 || strlen(filename) < 1)
714      return IMGTOOLERR_BADFILENAME;
715     
716   /* prepare directory entry */
717   ftype = option_resolution_lookup_int(opts, 'T');
718
719   switch (ftype) {
720      case 0:
721         entry.ftype         = 'T';
722         entry.start_address = 31465;
723         break;
724      case 1:
725         entry.ftype         = 'B';
726         entry.start_address = 31465; /* ??? */
727         break;
728      case 2:
729         entry.ftype         = 'D';
730         entry.start_address = 31465; /* ??? */
731         break;
732      default:
733         break;
734   }
735   
736   entry.delimitor = ':';
737   memset(&entry.fname, 0x20, 8); /* pad with spaces */
738   memcpy(&entry.fname, filename, strlen(filename));     
739
740   /* write file to disk */
741   ret = vzdos_writefile(partition, 0, sourcef, &entry);
742   if (ret) return ret;
743   
744   return IMGTOOLERR_SUCCESS;
745}
746
747static imgtoolerr_t vzdos_diskimage_suggesttransfer(imgtool_partition *partition, const char *fname, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
748{
749   imgtoolerr_t ret;
750   imgtool_image *image = imgtool_partition_image(partition);
751   vzdos_dirent entry;
752   
753   if (fname) {
754
755      ret = vzdos_get_dirent_fname(image, fname, &entry);
756      if (ret) return ret;
757     
758      switch (entry.ftype) {
759         case 'B':
760            suggestions[0].viability = SUGGESTION_RECOMMENDED;
761            suggestions[0].filter = filter_vzsnapshot_getinfo;
762            suggestions[0].description = "VZ Snapshot";
763            suggestions[1].viability = SUGGESTION_POSSIBLE;
764            suggestions[1].filter = NULL;
765            suggestions[1].description = "Raw";
766            break;
767         case 'T':
768            suggestions[0].viability = SUGGESTION_RECOMMENDED;
769            suggestions[0].filter = filter_vzsnapshot_getinfo;
770            suggestions[0].description = "VZ Snapshot";
771            suggestions[1].viability = SUGGESTION_POSSIBLE;
772            suggestions[1].filter = NULL;
773            suggestions[1].description = "Raw";           
774            suggestions[2].viability = SUGGESTION_POSSIBLE;
775            suggestions[2].filter = filter_vzbas_getinfo;
776            suggestions[2].description = "Tokenized Basic";
777            break;
778         default:
779            suggestions[0].viability = SUGGESTION_RECOMMENDED;
780            suggestions[0].filter = NULL;
781            suggestions[0].description = "Raw";         
782      }
783     
784   } else {   
785      suggestions[0].viability = SUGGESTION_RECOMMENDED;
786      suggestions[0].filter = NULL;
787      suggestions[0].description = "Raw";
788      suggestions[1].viability = SUGGESTION_POSSIBLE;
789      suggestions[1].filter = filter_vzsnapshot_getinfo;
790      suggestions[1].description = "VZ Snapshot";
791   }
792     
793   return IMGTOOLERR_SUCCESS;
794}
795
796static imgtoolerr_t vzdos_diskimage_create(imgtool_image *img, imgtool_stream *stream, option_resolution *opts)
797{
798   imgtoolerr_t ret;
799   int track, sector;
800
801   for (track = 0; track < 40; track++) {
802      for (sector = 0; sector < 16; sector++) {
803         ret = vzdos_write_formatted_sector(img, track, sector);
804         if (ret) return ret;
805      }
806   }
807   
808   return IMGTOOLERR_SUCCESS;
809}
810
811/*********************************************************************
812   Imgtool vz filter code
813*********************************************************************/
814
815static imgtoolerr_t vzsnapshot_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
816{
817   imgtoolerr_t ret;
818   imgtool_image *image = imgtool_partition_image(partition);
819   vzdos_dirent entry;
820   UINT8 header[24];
821   
822   /* get directory entry from disk */   
823   ret = vzdos_get_dirent_fname(image, filename, &entry);
824   if (ret) return ret;
825
826   /* prepare header */
827   header[0] = 'V';
828   header[1] = 'Z';
829   header[2] = 'F';
830   
831   switch (entry.ftype) {
832      case 'B':
833         header[3] = '1';
834         header[21] = 0xF1;
835         break;
836      case 'T':
837         header[3] = '0';
838         header[21] = 0xF0;   
839         break;
840      default:
841         memset(header, 0x00, 4);
842         header[21] = 0x00;
843   }
844     
845   memset(header + 4, 0x00, 17);
846   memcpy(header + 4, entry.fname, vzdos_get_fname_len(entry.fname) + 1);
847   place_integer_le(header, 22, 2, entry.start_address);
848
849   /* write header to file */
850   stream_write(destf, header, sizeof(header));
851
852   /* write data to file */
853   ret = vzdos_diskimage_readfile(partition, filename, "", destf);
854   if (ret) return ret;
855
856   return IMGTOOLERR_SUCCESS;
857}
858
859static imgtoolerr_t vzsnapshot_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
860{
861   imgtoolerr_t ret;
862   int fnameopt;
863   vzdos_dirent entry;
864   UINT8 header[24];
865
866   /* get header infos from file */
867   stream_read(sourcef, header, sizeof(header));
868   
869   /* prepare directory entry */   
870   entry.ftype         = header[21] == 0xF1 ? 'B' : 'T';
871   entry.delimitor     = ':';
872   entry.start_address = pick_integer_le(header, 22, 2);
873   
874   /* filename from header or directly? */
875   fnameopt = option_resolution_lookup_int(opts, 'F');
876   
877   if (fnameopt == 0) {
878      memcpy(&entry.fname, &header[4], 8);         
879   } else {
880      /* TODO: check for leading spaces and strip */
881      if (strlen(filename) > 8 || strlen(filename) < 1)
882      return IMGTOOLERR_BADFILENAME;
883     
884      memcpy(&entry.fname, filename, strlen(filename) - 3);
885   }
886   
887   /* write file to disk */
888   ret = vzdos_writefile(partition, 24, sourcef, &entry);
889   if (ret) return ret;
890
891   return IMGTOOLERR_SUCCESS;
892}
893
894void filter_vzsnapshot_getinfo(UINT32 state, union filterinfo *info)
895{
896   switch(state)
897   {
898      case FILTINFO_STR_NAME:         info->s = "vzsnapshot"; break;
899      case FILTINFO_STR_HUMANNAME:   info->s = "VZ Snapshot"; break;
900      case FILTINFO_STR_EXTENSION:   info->s = "vz"; break;
901      case FILTINFO_PTR_READFILE:      info->read_file = vzsnapshot_readfile; break;
902      case FILTINFO_PTR_WRITEFILE:   info->write_file = vzsnapshot_writefile; break;
903   }
904}
905
906/*********************************************************************
907   Imgtool module declaration
908*********************************************************************/
909
910OPTION_GUIDE_START(vzdos_writefile_optionguide)
911   OPTION_ENUM_START( 'T', "ftype",  "File type" )
912      OPTION_ENUM(     0, "basic",  "Basic"  )
913      OPTION_ENUM(     1, "binary", "Binary" )
914      OPTION_ENUM(     2, "data",   "Data"   )
915   OPTION_ENUM_END
916   OPTION_ENUM_START( 'F', "fname", "Filename" )
917      OPTION_ENUM(     0, "intern", "Filename from VZ-Header" )
918      OPTION_ENUM(     1, "extern", "Actual filename"         )
919   OPTION_ENUM_END
920OPTION_GUIDE_END
921
922/*
923T   Basic Editor File     
924B   Binary File     
925D   Sequential Access Program Data File     
926F   Quickwrite Document       
927A   Russell Harrison's Edit Ass. File     
928S   Dave Mitchell/Mark Hardwood Edit Ass. File  Start Addr A280H   
929S   Quickwrite/Diskops System File/Label       Except Above   
930W   Edit Ass. with Diskops File   Start           Addr A813H   
931W   E & F Word Pro with Patch 3.3 File           End Addr D000H   
932W   Russell Harrison Word Pro File              Except above two   
933*/
934
935void vzdos_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
936{
937   switch(state)
938   {
939      /* --- the following bits of info are returned as 64-bit signed integers --- */
940      case IMGTOOLINFO_INT_PREFER_UCASE:               info->i = 1; break;
941      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(vz_iterator); break;
942
943      /* --- the following bits of info are returned as NULL-terminated strings --- */
944      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "vzdos"); break;
945      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "VZ-DOS format"); break;
946      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
947      case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC:            strcpy(info->s = imgtool_temp_str(), "T[0]-2;F[0]-1"); break;
948      case IMGTOOLINFO_STR_EOLN:                     info->s = NULL; break;
949
950      /* --- the following bits of info are returned as pointers to data or functions --- */
951      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
952      case IMGTOOLINFO_PTR_OPEN:                     info->open = NULL; break;
953      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = vzdos_diskimage_beginenum; break;
954      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = vzdos_diskimage_nextenum; break;
955      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = vzdos_diskimage_freespace; break;
956      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = vzdos_diskimage_readfile; break;
957      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = vzdos_diskimage_writefile; break;
958      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = vzdos_diskimage_deletefile; break;
959      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = vzdos_diskimage_create; break;
960      case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE:         info->writefile_optguide = vzdos_writefile_optionguide; break;
961      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = vzdos_diskimage_suggesttransfer; break;
962      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_vz; break;
963   }
964}
src/mess/tools/imgtool/prodos.c
r1339r1340
1/****************************************************************************
2
3   prodos.c
4
5   Apple II ProDOS disk images
6
7*****************************************************************************
8
9  Notes:
10  - ProDOS disks are split into 512 byte blocks.
11
12  ProDOS directory structure:
13
14  Offset  Length  Description
15  ------  ------  -----------
16       0       2  ???
17       2       2  Next block (0 if end)
18       4      39  Directory Entry
19      43      39  Directory Entry
20                  ...
21     472      39  Directory Entry
22     511       1  ???
23
24
25  ProDOS directory entry structure:
26
27  Offset  Length  Description
28  ------  ------  -----------
29       0       1  Storage type (bits 7-4)
30                     10 - Seedling File (1 block)
31                 20 - Sapling File (2-256 blocks)
32                 30 - Tree File (257-32768 blocks)
33                 40 - Pascal Areas on ProFile HDs (???)
34                 50 - GS/OS Extended File (data and rsrc fork)
35                 E0 - Subdirectory Header
36                  F0 - Volume Header
37       1      15  File name (NUL padded)
38      16       1  File type
39      17       2  Key pointer
40      19       2  Blocks used
41      21       3  File size
42      24       4  Creation date
43      28       1  ProDOS version that created the file
44      29       1  Minimum ProDOS version needed to read the file
45      30       1  Access byte
46      31       2  Auxilary file type
47      33       4  Last modified date
48      37       2  Header pointer
49
50
51  In "seedling files", the key pointer points to a single block that is the
52  whole file.  In "sapling files", the key pointer points to an index block
53  that contains 256 2-byte index pointers that point to the actual blocks of
54  the files.  These 2-byte values are not contiguous; the low order byte is
55  in the first half of the block, and the high order byte is in the second
56  half of the block.  In "tree files", the key pointer points to an index
57  block of index blocks.
58
59  ProDOS dates are 32-bit little endian values
60
61   bits  0- 4   Day
62   bits  5- 8   Month (0-11)
63   bits  9-15   Year (0-49 is 2000-2049, 50-99 is 1950-1999)
64   bits 16-21   Minute
65   bits 24-28   Hour
66
67
68  ProDOS directory and volume headers have this information:
69
70  Offset  Length  Description
71  ------  ------  -----------
72      31       1  Length of the entry; generally is 39
73     32       1  Number of entries per block; generally is 13
74     33       2  Active entry count in directory
75     35       2  Volume bitmap block number
76     37       2  Total blocks on volume
77
78  GS/OS Extended Files (storage type $5) point to an extended key block that
79  contains information about the two forks.  The first half of the extended
80  key block contains info about the data form, and the second half the
81  resource fork.  Both sides have the following format:
82
83  Offset  Length  Description
84  ------  ------  -----------
85       0       1  Storage type (bits 3-0, unlike the directory entry)
86      1       2  Key pointer
87      3       2  Blocks used
88      5       3  File size
89      8       1  Size of secondary info #1 (must be 18 to be valid)
90      9       1  Secondary info #1 type (1=FInfo 2=xFInfo)
91     10      16  FInfo or xFInfo
92     26       1  Size of secondary info #2 (must be 18 to be valid)
93     27       1  Secondary info #2 type (1=FInfo 2=xFInfo)
94     28      16  FInfo or xFInfo
95
96  FInfo format:
97
98  Offset  Length  Description
99  ------  ------  -----------
100       0       4  File type
101      4       4  File creator
102      8       2  Finder flags
103      10       2  X Coordinate
104     12       2  Y Coordinate
105     14       2  Finder folder
106
107  xFInfo format:
108
109  Offset  Length  Description
110  ------  ------  -----------
111       0       2  Icon ID
112      2       6  Reserved
113      8       1  Script Code
114      9       1  Extended flags
115      10       2  Comment ID
116     12       4  Put Away Directory
117
118
119  For more info, consult ProDOS technical note #25
120   (http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.25.html)
121
122*****************************************************************************/
123
124#include "imgtool.h"
125#include "formats/ap2_dsk.h"
126#include "formats/ap_dsk35.h"
127#include "iflopimg.h"
128#include "macutil.h"
129
130#define   ROOTDIR_BLOCK         2
131#define BLOCK_SIZE            512
132
133typedef struct _prodos_diskinfo prodos_diskinfo;
134struct _prodos_diskinfo
135{
136   imgtoolerr_t (*load_block)(imgtool_image *image, int block, void *buffer);
137   imgtoolerr_t (*save_block)(imgtool_image *image, int block, const void *buffer);
138   UINT8 dirent_size;
139   UINT8 dirents_per_block;
140   UINT16 volume_bitmap_block;
141   UINT16 total_blocks;
142};
143
144typedef struct _prodos_direnum prodos_direnum;
145struct _prodos_direnum
146{
147   UINT32 block;
148   UINT32 index;
149   UINT8 block_data[BLOCK_SIZE];
150};
151
152typedef struct _prodos_dirent prodos_dirent;
153struct _prodos_dirent
154{
155   char filename[16];
156   UINT8 storage_type;
157   UINT16 extkey_pointer;
158   UINT16 key_pointer[2];
159   UINT32 filesize[2];
160   int depth[2];
161   UINT32 lastmodified_time;
162   UINT32 creation_time;
163
164   /* FInfo */
165   UINT32 file_type;
166   UINT32 file_creator;
167   UINT16 finder_flags;
168   UINT16 coord_x;
169   UINT16 coord_y;
170   UINT16 finder_folder;
171
172   /* xFInfo */
173   UINT16 icon_id;
174   UINT8 script_code;
175   UINT8 extended_flags;
176   UINT16 comment_id;
177   UINT32 putaway_directory;
178};
179
180typedef enum
181{
182   CREATE_NONE,
183   CREATE_FILE,
184   CREATE_DIR
185} creation_policy_t;
186
187
188
189static time_t prodos_crack_time(UINT32 prodos_time)
190{
191   struct tm t;
192   time_t now;
193
194   time(&now);
195   t = *localtime(&now);
196
197   t.tm_sec   = 0;
198   t.tm_min   = (prodos_time >> 16) & 0x3F;
199   t.tm_hour   = (prodos_time >> 24) & 0x1F;
200   t.tm_mday   = (prodos_time >>  0) & 0x1F;
201   t.tm_mon   = (prodos_time >>  5) & 0x0F;
202   t.tm_year   = (prodos_time >>  9) & 0x7F;
203
204   if (t.tm_year <= 49)
205      t.tm_year += 100;
206   return mktime(&t);
207}
208
209
210
211static UINT32 prodos_setup_time(time_t ansi_time)
212{
213   struct tm t;
214   UINT32 result = 0;
215
216   t = *localtime(&ansi_time);
217   if ((t.tm_year >= 100) && (t.tm_year <= 149))
218      t.tm_year -= 100;
219
220   result |= (((UINT32) t.tm_min)   & 0x003F) << 16;
221   result |= (((UINT32) t.tm_hour)   & 0x001F) << 24;
222   result |= (((UINT32) t.tm_mday)   & 0x001F) <<  0;
223   result |= (((UINT32) t.tm_mon)   & 0x000F) <<  5;
224   result |= (((UINT32) t.tm_year)   & 0x007F) <<  9;
225   return result;
226}
227
228
229
230static UINT32 prodos_time_now(void)
231{
232   time_t now;
233   time(&now);
234   return prodos_setup_time(now);
235}
236
237
238
239static int is_file_storagetype(UINT8 storage_type)
240{
241   return ((storage_type >= 0x10) && (storage_type <= 0x3F))
242      || ((storage_type >= 0x50) && (storage_type <= 0x5F));
243}
244
245
246
247static int is_normalfile_storagetype(UINT8 storage_type)
248{
249   return ((storage_type >= 0x10) && (storage_type <= 0x3F));
250}
251
252
253
254static int is_extendedfile_storagetype(UINT8 storage_type)
255{
256   return ((storage_type >= 0x50) && (storage_type <= 0x5F));
257}
258
259
260
261static int is_dir_storagetype(UINT8 storage_type)
262{
263   return (storage_type >= 0xE0) && (storage_type <= 0xEF);
264}
265
266
267
268static prodos_diskinfo *get_prodos_info(imgtool_image *image)
269{
270   prodos_diskinfo *info;
271   info = (prodos_diskinfo *) imgtool_floppy_extrabytes(image);
272   return info;
273}
274
275
276
277/* ----------------------------------------------------------------------- */
278
279static void prodos_find_block_525(imgtool_image *image, int block,
280   UINT32 *track, UINT32 *head, UINT32 *sector1, UINT32 *sector2)
281{
282   static const UINT8 skewing[] =
283   {
284      0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E,
285      0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F
286   };
287
288   block *= 2;
289
290   *track = block / APPLE2_SECTOR_COUNT;
291   *head = 0;
292   *sector1 = skewing[block % APPLE2_SECTOR_COUNT + 0];
293   *sector2 = skewing[block % APPLE2_SECTOR_COUNT + 1];
294}
295
296
297
298static imgtoolerr_t prodos_load_block_525(imgtool_image *image,
299   int block, void *buffer)
300{
301   floperr_t ferr;
302   UINT32 track, head, sector1, sector2;
303
304   prodos_find_block_525(image, block, &track, &head, &sector1, &sector2);
305
306   /* read first sector */
307   ferr = floppy_read_sector(imgtool_floppy(image), head, track,
308      sector1, 0, ((UINT8 *) buffer) + 0, 256);
309   if (ferr)
310      return imgtool_floppy_error(ferr);
311
312   /* read second sector */
313   ferr = floppy_read_sector(imgtool_floppy(image), head, track,
314      sector2, 0, ((UINT8 *) buffer) + 256, 256);
315   if (ferr)
316      return imgtool_floppy_error(ferr);
317
318   return IMGTOOLERR_SUCCESS;
319}
320
321
322
323static imgtoolerr_t prodos_save_block_525(imgtool_image *image,
324   int block, const void *buffer)
325{
326   floperr_t ferr;
327   UINT32 track, head, sector1, sector2;
328
329   prodos_find_block_525(image, block, &track, &head, &sector1, &sector2);
330
331   /* read first sector */
332   ferr = floppy_write_sector(imgtool_floppy(image), head, track,
333      sector1, 0, ((const UINT8 *) buffer) + 0, 256);
334   if (ferr)
335      return imgtool_floppy_error(ferr);
336
337   /* read second sector */
338   ferr = floppy_write_sector(imgtool_floppy(image), head, track,
339      sector2, 0, ((const UINT8 *) buffer) + 256, 256);
340   if (ferr)
341      return imgtool_floppy_error(ferr);
342
343   return IMGTOOLERR_SUCCESS;
344}
345
346
347
348static void prodos_setprocs_525(imgtool_image *image)
349{
350   prodos_diskinfo *info;
351   info = get_prodos_info(image);
352   info->load_block = prodos_load_block_525;
353   info->save_block = prodos_save_block_525;
354}
355
356
357
358/* ----------------------------------------------------------------------- */
359
360static imgtoolerr_t prodos_find_block_35(imgtool_image *image, int block,
361   UINT32 *track, UINT32 *head, UINT32 *sector)
362{
363   int sides = 2;
364
365   *track = 0;
366   while(block >= (apple35_sectors_per_track(imgtool_floppy(image), *track) * sides))
367   {
368      block -= (apple35_sectors_per_track(imgtool_floppy(image), (*track)++) * sides);
369      if (*track >= 80)
370         return IMGTOOLERR_SEEKERROR;
371   }
372
373   *head = block / apple35_sectors_per_track(imgtool_floppy(image), *track);
374   *sector = block % apple35_sectors_per_track(imgtool_floppy(image), *track);
375   return IMGTOOLERR_SUCCESS;
376}
377
378
379
380static imgtoolerr_t prodos_load_block_35(imgtool_image *image,
381   int block, void *buffer)
382{
383   imgtoolerr_t err;
384   floperr_t ferr;
385   UINT32 track, head, sector;
386
387   err = prodos_find_block_35(image, block, &track, &head, &sector);
388   if (err)
389      return err;
390
391   ferr = floppy_read_sector(imgtool_floppy(image), head, track, sector, 0, buffer, 512);
392   if (ferr)
393      return imgtool_floppy_error(ferr);
394
395   return IMGTOOLERR_SUCCESS;
396}
397
398
399
400static imgtoolerr_t prodos_save_block_35(imgtool_image *image,
401   int block, const void *buffer)
402{
403   imgtoolerr_t err;
404   floperr_t ferr;
405   UINT32 track, head, sector;
406
407   err = prodos_find_block_35(image, block, &track, &head, &sector);
408   if (err)
409      return err;
410
411   ferr = floppy_write_sector(imgtool_floppy(image), head, track, sector, 0, buffer, 512);
412   if (ferr)
413      return imgtool_floppy_error(ferr);
414
415   return IMGTOOLERR_SUCCESS;
416}
417
418
419
420static void prodos_setprocs_35(imgtool_image *image)
421{
422   prodos_diskinfo *info;
423   info = get_prodos_info(image);
424   info->load_block = prodos_load_block_35;
425   info->save_block = prodos_save_block_35;
426}
427
428
429
430/* ----------------------------------------------------------------------- */
431
432static imgtoolerr_t prodos_load_block(imgtool_image *image,
433   int block, void *buffer)
434{
435   prodos_diskinfo *diskinfo;
436   diskinfo = get_prodos_info(image);
437   return diskinfo->load_block(image, block, buffer);
438}
439
440
441
442static imgtoolerr_t prodos_save_block(imgtool_image *image,
443   int block, const void *buffer)
444{
445   prodos_diskinfo *diskinfo;
446   diskinfo = get_prodos_info(image);
447   return diskinfo->save_block(image, block, buffer);
448}
449
450
451
452static imgtoolerr_t prodos_clear_block(imgtool_image *image, int block)
453{
454   UINT8 buffer[BLOCK_SIZE];
455   memset(buffer, 0, sizeof(buffer));
456   return prodos_save_block(image, block, buffer);
457}
458
459
460
461/* ----------------------------------------------------------------------- */
462
463static imgtoolerr_t prodos_diskimage_open(imgtool_image *image)
464{
465   imgtoolerr_t err;
466   UINT8 buffer[BLOCK_SIZE];
467   prodos_diskinfo *di;
468   const UINT8 *ent;
469
470   di = get_prodos_info(image);
471
472   /* specify defaults */
473   di->dirent_size = 39;
474   di->dirents_per_block = 13;
475
476   /* load the first block, hoping that the volume header is first */
477   err = prodos_load_block(image, ROOTDIR_BLOCK, buffer);
478   if (err)
479      return err;
480
481   ent = &buffer[4];
482
483   /* did we find the volume header? */
484   if ((ent[0] & 0xF0) == 0xF0)
485   {
486      di->dirent_size         = pick_integer_le(ent, 31, 1);
487      di->dirents_per_block   = pick_integer_le(ent, 32, 1);
488      di->volume_bitmap_block   = pick_integer_le(ent, 35, 2);
489      di->total_blocks      = pick_integer_le(ent, 37, 2);
490   }
491
492   /* sanity check these values */
493   if (di->dirent_size < 39)
494      return IMGTOOLERR_CORRUPTIMAGE;
495   if (di->dirents_per_block * di->dirent_size >= BLOCK_SIZE)
496      return IMGTOOLERR_CORRUPTIMAGE;
497   if (di->volume_bitmap_block >= di->total_blocks)
498      return IMGTOOLERR_CORRUPTIMAGE;
499
500   return IMGTOOLERR_SUCCESS;
501}
502
503
504
505static imgtoolerr_t prodos_diskimage_open_525(imgtool_image *image, imgtool_stream *stream)
506{
507   prodos_setprocs_525(image);
508   return prodos_diskimage_open(image);
509}
510
511
512
513static imgtoolerr_t prodos_diskimage_open_35(imgtool_image *image, imgtool_stream *stream)
514{
515   prodos_setprocs_35(image);
516   return prodos_diskimage_open(image);
517}
518
519
520
521/* ----------------------------------------------------------------------- */
522
523static imgtoolerr_t prodos_load_volume_bitmap(imgtool_image *image, UINT8 **bitmap)
524{
525   imgtoolerr_t err;
526   prodos_diskinfo *di;
527   UINT8 *alloc_bitmap;
528   UINT32 bitmap_blocks, i;
529
530   di = get_prodos_info(image);
531
532   bitmap_blocks = (di->total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
533   alloc_bitmap = malloc(bitmap_blocks * BLOCK_SIZE);
534   if (!alloc_bitmap)
535   {
536      err = IMGTOOLERR_OUTOFMEMORY;
537      goto done;
538   }
539
540   for (i = 0; i < bitmap_blocks; i++)
541   {
542      err = prodos_load_block(image, di->volume_bitmap_block + i,
543         &alloc_bitmap[i * BLOCK_SIZE]);
544      if (err)
545         goto done;
546   }
547
548   err = IMGTOOLERR_SUCCESS;
549
550done:
551   if (err && alloc_bitmap)
552   {
553      free(alloc_bitmap);
554      alloc_bitmap = NULL;
555   }
556   *bitmap = alloc_bitmap;
557   return err;
558}
559
560
561
562static imgtoolerr_t prodos_save_volume_bitmap(imgtool_image *image, const UINT8 *bitmap)
563{
564   imgtoolerr_t err;
565   prodos_diskinfo *di;
566   UINT32 bitmap_blocks, i;
567
568   di = get_prodos_info(image);
569
570   bitmap_blocks = (di->total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
571
572   for (i = 0; i < bitmap_blocks; i++)
573   {
574      err = prodos_save_block(image, di->volume_bitmap_block + i,
575         &bitmap[i * BLOCK_SIZE]);
576      if (err)
577         return err;
578   }
579   return IMGTOOLERR_SUCCESS;
580}
581
582
583
584static void prodos_set_volume_bitmap_bit(UINT8 *buffer, UINT16 block, int value)
585{
586   UINT8 mask;
587   buffer += block / 8;
588   mask = 1 << (7 - (block % 8));
589   if (value)
590      *buffer |= mask;
591   else
592      *buffer &= ~mask;
593}
594
595
596
597static int prodos_get_volume_bitmap_bit(const UINT8 *buffer, UINT16 block)
598{
599   UINT8 mask;
600   buffer += block / 8;
601   mask = 1 << (7 - (block % 8));
602   return (*buffer & mask) ? 1 : 0;
603}
604
605
606
607static imgtoolerr_t prodos_alloc_block(imgtool_image *image, UINT8 *bitmap,
608   UINT16 *block)
609{
610   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
611   prodos_diskinfo *di;
612   UINT16 bitmap_blocks, i;
613   UINT8 *alloc_bitmap = NULL;
614
615   di = get_prodos_info(image);
616   *block = 0;
617   bitmap_blocks = (di->total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
618
619   if (!bitmap)
620   {
621      err = prodos_load_volume_bitmap(image, &alloc_bitmap);
622      if (err)
623         goto done;
624      bitmap = alloc_bitmap;
625   }
626
627   for (i = (di->volume_bitmap_block + bitmap_blocks); i < di->total_blocks; i++)
628   {
629      if (!prodos_get_volume_bitmap_bit(bitmap, i))
630      {
631         prodos_set_volume_bitmap_bit(bitmap, i, 1);
632         *block = i;
633         break;
634      }
635   }
636
637   if (*block > 0)
638   {
639      if (alloc_bitmap)
640      {
641         err = prodos_save_volume_bitmap(image, bitmap);
642         if (err)
643            goto done;
644      }
645   }
646   else
647   {
648      err = IMGTOOLERR_NOSPACE;
649   }
650
651done:
652   if (err)
653      *block = 0;
654   if (alloc_bitmap)
655      free(alloc_bitmap);
656   return err;
657}
658
659
660
661/* ----------------------------------------------------------------------- */
662
663static imgtoolerr_t prodos_diskimage_create(imgtool_image *image, option_resolution *opts)
664{
665   imgtoolerr_t err;
666   UINT32 heads, tracks, sectors, sector_bytes;
667   UINT32 dirent_size, volume_bitmap_block, i;
668   UINT32 volume_bitmap_block_count, total_blocks;
669   UINT8 buffer[BLOCK_SIZE];
670
671   heads = option_resolution_lookup_int(opts, 'H');
672   tracks = option_resolution_lookup_int(opts, 'T');
673   sectors = option_resolution_lookup_int(opts, 'S');
674   sector_bytes = option_resolution_lookup_int(opts, 'L');
675
676   dirent_size = 39;
677   volume_bitmap_block = 6;
678   total_blocks = tracks * heads * sectors * sector_bytes / BLOCK_SIZE;
679   volume_bitmap_block_count = (total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
680
681   /* prepare initial dir block */
682   memset(buffer, 0, sizeof(buffer));
683   place_integer_le(buffer, 4 +  0, 1, 0xF0);
684   place_integer_le(buffer, 4 + 31, 1, dirent_size);
685   place_integer_le(buffer, 4 + 32, 1, BLOCK_SIZE / dirent_size);
686   place_integer_le(buffer, 4 + 35, 2, volume_bitmap_block);
687   place_integer_le(buffer, 4 + 37, 2, total_blocks);
688
689   err = prodos_save_block(image, ROOTDIR_BLOCK, buffer);
690   if (err)
691      return err;
692
693   /* setup volume bitmap */
694   memset(buffer, 0, sizeof(buffer));
695   for (i = 0; i < (volume_bitmap_block + volume_bitmap_block_count); i++)
696      prodos_set_volume_bitmap_bit(buffer, i, 1);
697   prodos_save_block(image, volume_bitmap_block, buffer);
698
699   /* and finally open the image */
700   return prodos_diskimage_open(image);
701}
702
703
704
705static imgtoolerr_t prodos_diskimage_create_525(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
706{
707   prodos_setprocs_525(image);
708   return prodos_diskimage_create(image, opts);
709}
710
711
712
713static imgtoolerr_t prodos_diskimage_create_35(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
714{
715   prodos_setprocs_35(image);
716   return prodos_diskimage_create(image, opts);
717}
718
719
720
721/* ----------------------------------------------------------------------- */
722
723static imgtoolerr_t prodos_enum_seek(imgtool_image *image,
724   prodos_direnum *appleenum, UINT32 block, UINT32 index)
725{
726   imgtoolerr_t err;
727   UINT8 buffer[BLOCK_SIZE];
728
729   if (appleenum->block != block)
730   {
731      if (block != 0)
732      {
733         err = prodos_load_block(image, block, buffer);
734         if (err)
735            return err;
736         memcpy(appleenum->block_data, buffer, sizeof(buffer));
737      }
738      appleenum->block = block;
739   }
740
741   appleenum->index = index;
742   return IMGTOOLERR_SUCCESS;
743}
744
745
746
747static UINT8 *next_info_block(UINT8 *buffer, size_t *position)
748{
749   size_t side = *position & 0x100;
750   size_t subpos = *position & 0x0FF;
751   UINT8 *result;
752
753   if (subpos < 8)
754   {
755      subpos = 8;
756      *position = side + subpos;
757   }
758
759   while((buffer[side + subpos] == 0x00) || (subpos + buffer[side + subpos] > 0x100))
760   {
761      if (side)
762         return NULL;
763     
764      side = 0x100;
765      subpos = 8;
766   }
767
768   result = &buffer[side + subpos];
769   subpos += *result;
770   *position = side + subpos;
771   return result;
772}
773
774
775
776static UINT8 *alloc_info_block(UINT8 *buffer, size_t block_size, UINT8 block_type)
777{
778   size_t position = 0;
779   size_t side;
780   size_t subpos;
781   UINT8 *result;
782
783   while(next_info_block(buffer, &position))
784      ;
785
786   side = position & 0x100;
787   subpos = position & 0x0FF;
788
789   if ((subpos + block_size) > 0x100)
790      return NULL;
791
792   result = &buffer[side + subpos];
793   *(result++) = (UINT8) block_size;
794   *(result++) = block_type;
795   memset(result, 0, block_size - 2);
796   return result;
797}
798
799
800
801static imgtoolerr_t prodos_get_next_dirent(imgtool_image *image,
802   prodos_direnum *appleenum, prodos_dirent *ent)
803{
804   imgtoolerr_t err;
805   prodos_diskinfo *di;
806   size_t finfo_offset;
807   UINT32 next_block, next_index;
808   UINT32 offset;
809   UINT8 buffer[BLOCK_SIZE];
810   const UINT8 *info_ptr;
811   mac_fork_t fork_num;
812
813   di = get_prodos_info(image);
814   memset(ent, 0, sizeof(*ent));
815
816   /* have we hit the end of the file? */
817   if (appleenum->block == 0)
818      return IMGTOOLERR_SUCCESS;
819
820   /* populate the resulting dirent */
821   offset = appleenum->index * di->dirent_size + 4;
822   ent->storage_type = appleenum->block_data[offset + 0];
823   memcpy(ent->filename, &appleenum->block_data[offset + 1], 15);
824   ent->filename[15] = '\0';
825   ent->creation_time      = pick_integer_le(appleenum->block_data, offset + 24, 4);
826   ent->lastmodified_time   = pick_integer_le(appleenum->block_data, offset + 33, 4);
827   ent->file_type = 0x3F3F3F3F;
828   ent->file_creator = 0x3F3F3F3F;
829   ent->finder_flags  = 0;
830   ent->coord_x = 0;
831   ent->coord_y = 0;
832   ent->finder_folder = 0;
833   ent->icon_id = 0;
834   ent->script_code = 0;
835   ent->extended_flags = 0;
836   ent->comment_id = 0;
837   ent->putaway_directory = 0;
838
839   if (is_extendedfile_storagetype(ent->storage_type))
840   {
841      /* this is a ProDOS extended file; we need to get the extended info
842       * block */
843      ent->extkey_pointer   = pick_integer_le(appleenum->block_data, offset + 17, 2);
844
845      err = prodos_load_block(image, ent->extkey_pointer, buffer);
846      if (err)
847         return err;
848
849      for (fork_num = 0; fork_num <= 1; fork_num++)
850      {
851         ent->key_pointer[fork_num]   = pick_integer_le(buffer, 1 + (fork_num * 256), 2);
852         ent->filesize[fork_num]      = pick_integer_le(buffer, 5 + (fork_num * 256), 3);
853         ent->depth[fork_num]      = buffer[fork_num * 256] & 0x0F;
854      }
855
856      finfo_offset = 0;
857      while((info_ptr = next_info_block(buffer, &finfo_offset)) != NULL)
858      {
859         if (*(info_ptr++) == 18)
860         {
861            switch(*(info_ptr++))
862            {
863               case 1:   /* FInfo */
864                  ent->file_type     = pick_integer_be(info_ptr,  0, 4);
865                  ent->file_creator  = pick_integer_be(info_ptr,  4, 4);
866                  ent->finder_flags  = pick_integer_be(info_ptr,  8, 2);
867                  ent->coord_x       = pick_integer_be(info_ptr, 10, 2);
868                  ent->coord_y       = pick_integer_be(info_ptr, 12, 2);
869                  ent->finder_folder = pick_integer_be(info_ptr, 14, 4);
870                  break;
871
872               case 2:   /* xFInfo */
873                  ent->icon_id           = pick_integer_be(info_ptr,  0, 2);
874                  ent->script_code       = pick_integer_be(info_ptr,  8, 1);
875                  ent->extended_flags    = pick_integer_be(info_ptr,  9, 1);
876                  ent->comment_id        = pick_integer_be(info_ptr, 10, 2);
877                  ent->putaway_directory = pick_integer_be(info_ptr, 12, 4);
878                  break;
879            }
880         }
881      }
882   }
883   else
884   {
885      /* normal ProDOS files have all of the info right here */
886      ent->key_pointer[0]   = pick_integer_le(appleenum->block_data, offset + 17, 2);
887      ent->filesize[0]   = pick_integer_le(appleenum->block_data, offset + 21, 3);
888      ent->depth[0]      = ent->storage_type >> 4;
889   }
890
891   /* identify next entry */
892   next_block = appleenum->block;
893   next_index = appleenum->index + 1;
894   if (next_index >= di->dirents_per_block)
895   {
896      next_block = pick_integer_le(appleenum->block_data, 2, 2);
897      next_index = 0;
898   }
899
900   /* seek next block */
901   err = prodos_enum_seek(image, appleenum, next_block, next_index);
902   if (err)
903      return err;
904
905   return IMGTOOLERR_SUCCESS;
906}
907
908
909
910/* changes a normal file to a ProDOS extended file */
911static imgtoolerr_t prodos_promote_file(imgtool_image *image, UINT8 *bitmap, prodos_dirent *ent)
912{
913   imgtoolerr_t err;
914   UINT16 new_block;
915   UINT8 buffer[BLOCK_SIZE];
916
917   assert(is_normalfile_storagetype(ent->storage_type));
918
919   err = prodos_alloc_block(image, bitmap, &new_block);
920   if (err)
921      return err;
922
923   /* create raw extended info block */
924   memset(buffer, 0, sizeof(buffer));
925   err = prodos_save_block(image, new_block, buffer);
926   if (err)
927      return err;
928
929   ent->storage_type = (ent->storage_type & 0x0F) | 0x50;
930   ent->extkey_pointer = new_block;
931   return IMGTOOLERR_SUCCESS;
932}
933
934
935
936static imgtoolerr_t prodos_put_dirent(imgtool_image *image,
937   prodos_direnum *appleenum, prodos_dirent *ent)
938{
939   imgtoolerr_t err;
940   prodos_diskinfo *di;
941   UINT32 offset;
942   size_t finfo_offset;
943   UINT8 buffer[BLOCK_SIZE];
944   mac_fork_t fork_num;
945   int needs_finfo = FALSE;
946   int needs_xfinfo = FALSE;
947   UINT8 *info_ptr;
948   UINT8 *finfo;
949   UINT8 *xfinfo;
950
951   di = get_prodos_info(image);
952   offset = appleenum->index * di->dirent_size + 4;
953
954   /* determine whether we need FInfo and/or xFInfo */
955   if (is_normalfile_storagetype(ent->storage_type))
956   {
957      needs_finfo = (ent->file_type != 0x3F3F3F3F) ||
958         (ent->file_creator != 0x3F3F3F3F) ||
959         (ent->finder_flags != 0) ||
960         (ent->coord_x != 0) ||
961         (ent->coord_y != 0) ||
962         (ent->finder_folder != 0);
963
964      needs_xfinfo = (ent->icon_id != 0) ||
965         (ent->script_code != 0) ||
966         (ent->extended_flags != 0) ||
967         (ent->comment_id != 0) ||
968         (ent->putaway_directory != 0);
969   }
970
971   /* do we need to promote this file to an extended file? */
972   if (!is_extendedfile_storagetype(ent->storage_type)
973      && (needs_finfo || needs_xfinfo))
974   {
975      err = prodos_promote_file(image, NULL, ent);
976      if (err)
977         return err;
978   }
979
980   /* write out the storage type, filename, creation and lastmodified times */
981   appleenum->block_data[offset + 0] = ent->storage_type;
982   memcpy(&appleenum->block_data[offset + 1], ent->filename, 15);
983   place_integer_le(appleenum->block_data, offset + 24, 4, ent->creation_time);
984   place_integer_le(appleenum->block_data, offset + 33, 4, ent->lastmodified_time);
985
986   if (is_extendedfile_storagetype(ent->storage_type))
987   {
988      /* ProDOS extended file */
989      err = prodos_load_block(image, ent->extkey_pointer, buffer);
990      if (err)
991         return err;
992
993      finfo = NULL;
994      xfinfo = NULL;
995
996      for (fork_num = 0; fork_num <= 1; fork_num++)
997      {
998         place_integer_le(buffer, 1 + (fork_num * 256), 2, ent->key_pointer[fork_num]);
999         place_integer_le(buffer, 5 + (fork_num * 256), 3, ent->filesize[fork_num]);
1000         buffer[fork_num * 256] = ent->depth[fork_num];
1001      }
1002
1003      finfo_offset = 0;
1004      while((info_ptr = next_info_block(buffer, &finfo_offset)) != NULL)
1005      {
1006         if (*(info_ptr++) == 18)
1007         {
1008            switch(*(info_ptr++))
1009            {
1010               case 1:   /* FInfo */
1011                  finfo = info_ptr;
1012                  break;
1013
1014               case 2:   /* xFInfo */
1015                  xfinfo = info_ptr;
1016                  break;
1017            }
1018         }
1019      }
1020
1021      /* allocate the finfo and/or xinfo blocks, if we need them */
1022      if (needs_finfo && !finfo)
1023         finfo = alloc_info_block(buffer, 18, 1);
1024      if (needs_xfinfo && !xfinfo)
1025         xfinfo = alloc_info_block(buffer, 18, 2);
1026
1027      if (finfo)
1028      {
1029         place_integer_be(finfo,  0, 4, ent->file_type);
1030         place_integer_be(finfo,  4, 4, ent->file_creator);
1031         place_integer_be(finfo,  8, 2, ent->finder_flags);
1032         place_integer_be(finfo, 10, 2, ent->coord_x);
1033         place_integer_be(finfo, 12, 2, ent->coord_y);
1034         place_integer_be(finfo, 14, 4, ent->finder_folder);
1035      }
1036
1037      if (xfinfo)
1038      {
1039         place_integer_be(xfinfo,  0, 2, ent->icon_id);
1040         place_integer_be(xfinfo,  8, 1, ent->script_code);
1041         place_integer_be(xfinfo,  9, 1, ent->extended_flags);
1042         place_integer_be(xfinfo, 10, 2, ent->comment_id);
1043         place_integer_be(xfinfo, 12, 4, ent->putaway_directory);
1044      }
1045
1046      err = prodos_save_block(image, ent->extkey_pointer, buffer);
1047      if (err)
1048         return err;
1049
1050      place_integer_le(appleenum->block_data, offset + 17, 2, ent->extkey_pointer);
1051      place_integer_le(appleenum->block_data, offset + 21, 3, BLOCK_SIZE);
1052   }
1053   else
1054   {
1055      /* normal file */
1056      place_integer_le(appleenum->block_data, offset + 17, 2, ent->key_pointer[0]);
1057      place_integer_le(appleenum->block_data, offset + 21, 3, ent->filesize[0]);
1058   }
1059
1060   err = prodos_save_block(image, appleenum->block, appleenum->block_data);
1061   if (err)
1062      return err;
1063
1064   return IMGTOOLERR_SUCCESS;
1065}
1066
1067
1068
1069static imgtoolerr_t prodos_lookup_path(imgtool_image *image, const char *path,
1070   creation_policy_t create, prodos_direnum *direnum, prodos_dirent *ent)
1071{
1072   imgtoolerr_t err;
1073   prodos_direnum my_direnum;
1074   UINT32 block = ROOTDIR_BLOCK;
1075   const char *old_path;
1076   UINT16 this_block;
1077   UINT32 this_index;
1078   UINT16 free_block = 0;
1079   UINT32 free_index = 0;
1080   UINT16 new_file_block;
1081   UINT8 buffer[BLOCK_SIZE];
1082
1083   if (!direnum)
1084      direnum = &my_direnum;
1085
1086   while(*path)
1087   {
1088      memset(direnum, 0, sizeof(*direnum));
1089      err = prodos_enum_seek(image, direnum, block, 0);
1090      if (err)
1091         goto done;
1092
1093      do
1094      {
1095         this_block = direnum->block;
1096         this_index = direnum->index;
1097
1098         err = prodos_get_next_dirent(image, direnum, ent);
1099         if (err)
1100            goto done;
1101
1102         /* if we need to create a file entry and this is free, track it */
1103         if (create && this_block && !free_block && !ent->storage_type)
1104         {
1105            free_block = this_block;
1106            free_index = this_index;
1107         }
1108      }
1109      while(direnum->block && (strcmp(path, ent->filename) || (
1110         !is_file_storagetype(ent->storage_type) &&
1111         !is_dir_storagetype(ent->storage_type))));
1112
1113      old_path = path;
1114      path += strlen(path) + 1;   
1115      if (*path)
1116      {
1117         /* we have found part of the path; we are not finished yet */
1118         if (!is_dir_storagetype(ent->storage_type))
1119         {
1120            err = IMGTOOLERR_FILENOTFOUND;
1121            goto done;
1122         }
1123         block = ent->key_pointer[0];
1124      }
1125      else if (!direnum->block)
1126      {
1127         /* did not find file; maybe we need to create it */
1128         if (create == CREATE_NONE)
1129         {
1130            err = IMGTOOLERR_FILENOTFOUND;
1131            goto done;
1132         }
1133
1134         /* do we need to expand the directory? */
1135         if (!free_block)
1136         {
1137            if (this_block == 0)
1138            {
1139               err = IMGTOOLERR_CORRUPTFILE;
1140               goto done;
1141            }
1142
1143            err = prodos_load_block(image, this_block, buffer);
1144            if (err)
1145               goto done;
1146
1147            /* allocate a block */
1148            err = prodos_alloc_block(image, NULL, &free_block);
1149            if (err)
1150               goto done;
1151
1152            /* clear out this new block */
1153            err = prodos_clear_block(image, free_block);
1154            if (err)
1155               goto done;
1156
1157            /* save this link */
1158            place_integer_le(buffer, 2, 2, free_block);
1159            err = prodos_save_block(image, this_block, buffer);
1160            if (err)
1161               goto done;
1162
1163            free_index = 0;
1164         }
1165
1166         /* seek back to the free space */
1167         err = prodos_enum_seek(image, direnum, free_block, free_index);
1168         if (err)
1169            goto done;
1170
1171         new_file_block = 0;
1172         if (create == CREATE_DIR)
1173         {
1174            /* if we are creating a directory, we need to create a new block */
1175            err = prodos_alloc_block(image, NULL, &new_file_block);
1176            if (err)
1177               goto done;
1178
1179            err = prodos_clear_block(image, new_file_block);
1180            if (err)
1181               goto done;
1182         }
1183
1184         /* prepare the dirent */
1185         memset(ent, 0, sizeof(*ent));
1186         ent->storage_type = (create == CREATE_DIR) ? 0xe0 : 0x10;
1187         ent->creation_time = ent->lastmodified_time = prodos_time_now();
1188         ent->key_pointer[0] = new_file_block;
1189         ent->file_type = 0x3F3F3F3F;
1190         ent->file_creator = 0x3F3F3F3F;
1191         strncpy(ent->filename, old_path, sizeof(ent->filename) / sizeof(ent->filename[0]));
1192
1193         /* and place it */
1194         err = prodos_put_dirent(image, direnum, ent);
1195         if (err)
1196            goto done;
1197
1198         this_block = free_block;
1199         this_index = free_index;
1200      }
1201      else
1202      {
1203         /* we've found the file; seek that dirent */
1204         err = prodos_enum_seek(image, direnum, this_block, this_index);
1205         if (err)
1206            goto done;
1207      }
1208   }
1209
1210   err = IMGTOOLERR_SUCCESS;
1211done:
1212   return err;
1213}
1214
1215
1216
1217static imgtoolerr_t prodos_fill_file(imgtool_image *image, UINT8 *bitmap,
1218   UINT16 key_block, int key_block_allocated,
1219   int depth, UINT32 blockcount, UINT32 block_index)
1220{
1221   imgtoolerr_t err;
1222   prodos_diskinfo *di;
1223   int dirty;
1224   int sub_block_allocated;
1225   UINT16 i, sub_block, new_sub_block;
1226   UINT8 buffer[BLOCK_SIZE];
1227
1228   di = get_prodos_info(image);
1229
1230   if (key_block_allocated)
1231   {
1232      /* we are on a recently allocated key block; start fresh */
1233      memset(buffer, 0, sizeof(buffer));
1234      dirty = TRUE;
1235   }
1236   else
1237   {
1238      /* this is a preexisting key block */
1239      err = prodos_load_block(image, key_block, buffer);
1240      if (err)
1241         return err;
1242      dirty = FALSE;
1243   }
1244
1245   for (i = 0; i < 256; i++)
1246   {     
1247      sub_block_allocated = FALSE;
1248
1249      sub_block = buffer[i + 256];
1250      sub_block <<= 8;
1251      sub_block += buffer[i + 0];
1252
1253      new_sub_block = sub_block;
1254      if ((block_index < blockcount) && (sub_block == 0))
1255      {
1256         err = prodos_alloc_block(image, bitmap, &new_sub_block);
1257         if (err)
1258            return err;
1259         sub_block_allocated = TRUE;
1260      }
1261      else if ((block_index >= blockcount) && (sub_block != 0))
1262      {
1263         new_sub_block = 0;
1264         if (sub_block < di->total_blocks)
1265            prodos_set_volume_bitmap_bit(bitmap, sub_block, 0);
1266      }
1267
1268      /* did we change the block? */
1269      if (new_sub_block != sub_block)
1270      {
1271         dirty = TRUE;
1272         buffer[i + 0] = new_sub_block >> 0;
1273         buffer[i + 256] = new_sub_block >> 8;
1274         if (sub_block == 0)
1275            sub_block = new_sub_block;
1276      }
1277
1278      /* call recursive function */
1279      if (depth > 2)
1280      {
1281         err = prodos_fill_file(image, bitmap, sub_block, sub_block_allocated, depth - 1, blockcount, block_index);
1282         if (err)
1283            return err;
1284      }
1285
1286      /* increment index */
1287      block_index += 1 << ((depth - 2) * 8);
1288   }
1289
1290   /* if we changed anything, then save the block */
1291   if (dirty)
1292   {
1293      err = prodos_save_block(image, key_block, buffer);
1294      if (err)
1295         return err;
1296   }
1297   return IMGTOOLERR_SUCCESS;
1298}
1299
1300
1301
1302static imgtoolerr_t prodos_set_file_block_count(imgtool_image *image, prodos_direnum *direnum,
1303   prodos_dirent *ent, UINT8 *bitmap, int fork_num, UINT32 new_blockcount)
1304{
1305   imgtoolerr_t err;
1306   int depth, new_depth, i;
1307   UINT16 new_block, block;
1308   UINT8 buffer[BLOCK_SIZE];
1309   UINT16 key_pointer;
1310
1311   if (fork_num && (new_blockcount > 0) && !is_extendedfile_storagetype(ent->storage_type))
1312   {
1313      /* need to change a normal file to an extended file */
1314      err = prodos_promote_file(image, bitmap, ent);
1315      if (err)
1316         return err;
1317   }
1318
1319   key_pointer = ent->key_pointer[fork_num];
1320   depth = ent->depth[fork_num];
1321
1322   /* determine the new tree depth */
1323   if (new_blockcount <= 1)
1324      new_depth = 1;
1325   else if (new_blockcount <= 256)
1326      new_depth = 2;
1327   else
1328      new_depth = 3;
1329
1330   /* are we zero length, and do we have to create a block? */
1331   if ((new_blockcount >= 1) && (key_pointer == 0))
1332   {
1333      err = prodos_alloc_block(image, bitmap, &new_block);
1334      if (err)
1335         return err;
1336      key_pointer = new_block;
1337   }
1338
1339   /* do we have to grow the tree? */
1340   while(new_depth > depth)
1341   {
1342      err = prodos_alloc_block(image, bitmap, &new_block);
1343      if (err)
1344         return err;
1345
1346      /* create this new key block, with a link to the previous one */
1347      memset(buffer, 0, sizeof(buffer));
1348      buffer[0] = (UINT8) (key_pointer >> 0);
1349      buffer[256] = (UINT8) (key_pointer >> 8);
1350      err = prodos_save_block(image, new_block, buffer);
1351      if (err)
1352         return err;
1353
1354      depth++;
1355      key_pointer = new_block;
1356   }
1357
1358   /* do we have to shrink the tree? */
1359   while(new_depth < depth)
1360   {
1361      err = prodos_load_block(image, key_pointer, buffer);
1362      if (err)
1363         return err;
1364
1365      for (i = 1; i < 256; i++)
1366      {
1367         block = buffer[i + 256];
1368         block <<= 8;
1369         block |= buffer[i + 0];
1370
1371         if (block > 0)
1372         {
1373            if (depth > 2)
1374            {
1375               /* remove this block's children */
1376               err = prodos_fill_file(image, bitmap, block, FALSE, depth - 1, 0, 0);
1377               if (err)
1378                  return err;
1379            }
1380
1381            /* and remove this block */
1382            prodos_set_volume_bitmap_bit(bitmap, block, 0);
1383         }
1384      }
1385
1386      /* remove this key block */
1387      prodos_set_volume_bitmap_bit(bitmap, key_pointer, 0);
1388
1389      /* set the new key pointer */
1390      block = buffer[256];
1391      block <<= 8;
1392      block |= buffer[0];
1393      key_pointer = block;
1394   
1395      depth--;
1396   }
1397
1398   if (new_blockcount > 0)
1399   {
1400      /* fill out the file tree */
1401      err = prodos_fill_file(image, bitmap, key_pointer, FALSE, depth, new_blockcount, 0);
1402      if (err)
1403         return err;
1404   }
1405   else if (key_pointer != 0)
1406   {
1407      /* we are now zero length, and don't need a key pointer */
1408      prodos_set_volume_bitmap_bit(bitmap, key_pointer, 0);
1409      key_pointer = 0;
1410   }
1411
1412   /* change the depth if we are not an extended file */
1413   if (is_normalfile_storagetype(ent->storage_type))
1414   {
1415      ent->storage_type &= ~0xF0;
1416      ent->storage_type |= depth * 0x10;
1417   }
1418
1419   ent->key_pointer[fork_num] = key_pointer;
1420   ent->depth[fork_num] = depth;
1421   return IMGTOOLERR_SUCCESS;
1422}
1423
1424
1425
1426static imgtoolerr_t prodos_set_file_size(imgtool_image *image, prodos_direnum *direnum,
1427   prodos_dirent *ent, int fork_num, UINT32 new_size)
1428{
1429   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1430   UINT32 blockcount, new_blockcount;
1431   UINT8 *bitmap = NULL;
1432
1433   if (ent->filesize[fork_num] != new_size)
1434   {
1435      blockcount = (ent->filesize[fork_num] + BLOCK_SIZE - 1) / BLOCK_SIZE;
1436      new_blockcount = (new_size + BLOCK_SIZE - 1) / BLOCK_SIZE;
1437
1438      /* do we need to change the block chain? */
1439      if (new_blockcount != blockcount)
1440      {
1441         err = prodos_load_volume_bitmap(image, &bitmap);
1442         if (err)
1443            goto done;
1444
1445         err = prodos_set_file_block_count(image, direnum, ent, bitmap, fork_num, new_blockcount);
1446         if (err)
1447            goto done;
1448
1449         err = prodos_save_volume_bitmap(image, bitmap);
1450         if (err)
1451            goto done;
1452      }
1453
1454      ent->filesize[fork_num] = new_size;
1455      err = prodos_put_dirent(image, direnum, ent);
1456      if (err)
1457         goto done;
1458   }
1459
1460done:
1461   if (bitmap)
1462      free(bitmap);
1463   return err;
1464}
1465
1466
1467
1468static UINT32 prodos_get_storagetype_maxfilesize(UINT8 storage_type)
1469{
1470   UINT32 max_filesize = 0;
1471   switch(storage_type & 0xF0)
1472   {
1473      case 0x10:
1474         max_filesize = BLOCK_SIZE * 1;
1475         break;
1476      case 0x20:
1477         max_filesize = BLOCK_SIZE * 256;
1478         break;
1479      case 0x30:
1480      case 0x50:
1481         max_filesize = BLOCK_SIZE * 32768;
1482         break;
1483   }
1484   return max_filesize;
1485}
1486
1487
1488
1489static imgtoolerr_t prodos_diskimage_beginenum(imgtool_directory *enumeration, const char *path)
1490{
1491   imgtoolerr_t err;
1492   imgtool_image *image;
1493   prodos_direnum *appleenum;
1494   prodos_dirent ent;
1495   UINT16 block = ROOTDIR_BLOCK;
1496
1497   image = imgtool_directory_image(enumeration);
1498   appleenum = (prodos_direnum *) imgtool_directory_extrabytes(enumeration);
1499
1500   /* find subdirectory, if appropriate */
1501   if (*path)
1502   {
1503      err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
1504      if (err)
1505         return err;
1506
1507      /* only work on directories */
1508      if (!is_dir_storagetype(ent.storage_type))
1509         return IMGTOOLERR_FILENOTFOUND;
1510
1511      block = ent.key_pointer[0];
1512   }
1513
1514   /* seek initial block */
1515   err = prodos_enum_seek(image, appleenum, block, 0);
1516   if (err)
1517      return err;
1518
1519   return IMGTOOLERR_SUCCESS;
1520}
1521
1522
1523
1524static imgtoolerr_t prodos_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
1525{
1526   imgtoolerr_t err;
1527   imgtool_image *image;
1528   prodos_direnum *appleenum;
1529   prodos_dirent pd_ent;
1530   UINT32 max_filesize;
1531
1532   image = imgtool_directory_image(enumeration);
1533   appleenum = (prodos_direnum *) imgtool_directory_extrabytes(enumeration);
1534
1535   do
1536   {
1537      err = prodos_get_next_dirent(image, appleenum, &pd_ent);
1538      if (err)
1539         return err;
1540   }
1541   while(appleenum->block
1542      && !is_file_storagetype(pd_ent.storage_type)
1543      && !is_dir_storagetype(pd_ent.storage_type));
1544
1545   /* end of file? */
1546   if (pd_ent.storage_type == 0x00)
1547   {
1548      ent->eof = 1;
1549      return IMGTOOLERR_SUCCESS;
1550   }
1551
1552   strcpy(ent->filename, pd_ent.filename);
1553   ent->directory         = is_dir_storagetype(pd_ent.storage_type);
1554   ent->creation_time      = prodos_crack_time(pd_ent.creation_time);
1555   ent->lastmodified_time   = prodos_crack_time(pd_ent.lastmodified_time);
1556
1557   if (!ent->directory)
1558   {
1559      ent->filesize = pd_ent.filesize[0];
1560
1561      max_filesize = prodos_get_storagetype_maxfilesize(pd_ent.storage_type);
1562      if (ent->filesize > max_filesize)
1563      {
1564         ent->corrupt = 1;
1565         ent->filesize = max_filesize;
1566      }
1567   }
1568   return IMGTOOLERR_SUCCESS;
1569}
1570
1571
1572
1573static imgtoolerr_t prodos_read_file_tree(imgtool_image *image, UINT32 *filesize,
1574   UINT32 block, int nest_level, imgtool_stream *destf)
1575{
1576   imgtoolerr_t err;
1577   prodos_diskinfo *di;
1578   UINT8 buffer[BLOCK_SIZE];
1579   UINT16 sub_block;
1580   size_t bytes_to_write;
1581   int i;
1582
1583   /* check bounds */
1584   di = get_prodos_info(image);
1585   if (block >= di->total_blocks)
1586      return IMGTOOLERR_CORRUPTFILE;
1587
1588   err = prodos_load_block(image, block, buffer);
1589   if (err)
1590      return err;
1591
1592   if (nest_level > 0)
1593   {
1594      /* this is an index block */
1595      for (i = 0; i < 256; i++)
1596      {
1597         /* retrieve the block pointer; the two bytes are on either half
1598          * of the block */
1599         sub_block = buffer[i + 256];
1600         sub_block <<= 8;
1601         sub_block |= buffer[i + 0];
1602
1603         if (sub_block != 0)
1604         {
1605            err = prodos_read_file_tree(image, filesize, sub_block, nest_level - 1, destf);
1606            if (err)
1607               return err;
1608         }
1609      }
1610   }
1611   else
1612   {
1613      /* this is a leaf block */
1614      bytes_to_write = MIN(*filesize, sizeof(buffer));
1615      stream_write(destf, buffer, bytes_to_write);
1616      *filesize -= bytes_to_write;
1617   }
1618   return IMGTOOLERR_SUCCESS;
1619}
1620
1621
1622
1623static imgtoolerr_t prodos_write_file_tree(imgtool_image *image, UINT32 *filesize,
1624   UINT32 block, int nest_level, imgtool_stream *sourcef)
1625{
1626   imgtoolerr_t err;
1627   prodos_diskinfo *di;
1628   UINT8 buffer[BLOCK_SIZE];
1629   UINT16 sub_block;
1630   size_t bytes_to_read;
1631   int i;
1632
1633   /* nothing more to read? bail */
1634   if (*filesize == 0)
1635      return IMGTOOLERR_SUCCESS;
1636
1637   /* check bounds */
1638   di = get_prodos_info(image);
1639   if (block >= di->total_blocks)
1640      return IMGTOOLERR_CORRUPTFILE;
1641
1642   err = prodos_load_block(image, block, buffer);
1643   if (err)
1644      return err;
1645
1646   if (nest_level > 0)
1647   {
1648      for (i = 0; i < 256; i++)
1649      {
1650         sub_block = buffer[i + 256];
1651         sub_block <<= 8;
1652         sub_block |= buffer[i + 0];
1653
1654         if (sub_block != 0)
1655         {
1656            err = prodos_write_file_tree(image, filesize, sub_block, nest_level - 1, sourcef);
1657            if (err)
1658               return err;
1659         }
1660      }
1661   }
1662   else
1663   {
1664      /* this is a leaf block */
1665      bytes_to_read = MIN(*filesize, sizeof(buffer));
1666      stream_read(sourcef, buffer, bytes_to_read);
1667      *filesize -= bytes_to_read;
1668
1669      err = prodos_save_block(image, block, buffer);
1670      if (err)
1671         return err;
1672   }
1673   return IMGTOOLERR_SUCCESS;
1674}
1675
1676
1677
1678static imgtoolerr_t prodos_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
1679{
1680   imgtoolerr_t err;
1681   imgtool_image *image = imgtool_partition_image(partition);
1682   prodos_diskinfo *di;
1683   UINT8 *bitmap = NULL;
1684   UINT16 i;
1685
1686   di = get_prodos_info(image);
1687   *size = 0;
1688
1689   err = prodos_load_volume_bitmap(image, &bitmap);
1690   if (err)
1691      goto done;
1692
1693   for (i = 0; i < di->total_blocks; i++)
1694   {
1695      if (!prodos_get_volume_bitmap_bit(bitmap, i))
1696         *size += BLOCK_SIZE;
1697   }
1698
1699done:
1700   if (bitmap)
1701      free(bitmap);
1702   return err;
1703}
1704
1705
1706
1707static imgtoolerr_t prodos_diskimage_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
1708{
1709   imgtoolerr_t err;
1710   imgtool_image *image = imgtool_partition_image(partition);
1711   prodos_dirent ent;
1712   UINT16 key_pointer;
1713   int nest_level;
1714   mac_fork_t fork_num;
1715
1716   err = prodos_lookup_path(image, filename, CREATE_NONE, NULL, &ent);
1717   if (err)
1718      return err;
1719
1720   if (is_dir_storagetype(ent.storage_type))
1721      return IMGTOOLERR_FILENOTFOUND;
1722
1723   err = mac_identify_fork(fork, &fork_num);
1724   if (err)
1725      return err;
1726
1727   key_pointer = ent.key_pointer[fork_num];
1728   nest_level = ent.depth[fork_num] - 1;
1729
1730   if (key_pointer != 0)
1731   {
1732      err = prodos_read_file_tree(image, &ent.filesize[fork_num], key_pointer,
1733         nest_level, destf);
1734      if (err)
1735         return err;
1736   }
1737
1738   /* have we not actually received the correct amount of bytes? if not, fill in the rest */
1739   if (ent.filesize[fork_num] > 0)
1740      stream_fill(destf, 0, ent.filesize[fork_num]);
1741
1742   return IMGTOOLERR_SUCCESS;
1743}
1744
1745
1746
1747static imgtoolerr_t prodos_diskimage_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
1748{
1749   imgtoolerr_t err;
1750   imgtool_image *image = imgtool_partition_image(partition);
1751   prodos_dirent ent;
1752   prodos_direnum direnum;
1753   UINT64 file_size;
1754   mac_fork_t fork_num;
1755
1756   file_size = stream_size(sourcef);
1757
1758   err = prodos_lookup_path(image, filename, CREATE_FILE, &direnum, &ent);
1759   if (err)
1760      return err;
1761
1762   /* only work on files */
1763   if (is_dir_storagetype(ent.storage_type))
1764      return IMGTOOLERR_FILENOTFOUND;
1765
1766   err = mac_identify_fork(fork, &fork_num);
1767   if (err)
1768      return err;
1769
1770   /* set the file size */
1771   err = prodos_set_file_size(image, &direnum, &ent, fork_num, file_size);
1772   if (err)
1773      return err;
1774
1775   err = prodos_write_file_tree(image, &ent.filesize[fork_num], ent.key_pointer[fork_num],
1776      ent.depth[fork_num] - 1, sourcef);
1777   if (err)
1778      return err;
1779
1780   return IMGTOOLERR_SUCCESS;
1781}
1782
1783
1784
1785static imgtoolerr_t prodos_diskimage_deletefile(imgtool_partition *partition, const char *path)
1786{
1787   imgtoolerr_t err;
1788   imgtool_image *image = imgtool_partition_image(partition);
1789   prodos_dirent ent;
1790   prodos_direnum direnum;
1791
1792   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
1793   if (err)
1794      return err;
1795
1796   /* only work on files */
1797   if (is_dir_storagetype(ent.storage_type))
1798      return IMGTOOLERR_FILENOTFOUND;
1799
1800   /* empty out both forks */
1801   err = prodos_set_file_size(image, &direnum, &ent, 0, 0);
1802   if (err)
1803      return err;
1804   err = prodos_set_file_size(image, &direnum, &ent, 1, 0);
1805   if (err)
1806      return err;
1807
1808   memset(&ent, 0, sizeof(ent));
1809   err = prodos_put_dirent(image, &direnum, &ent);
1810   if (err)
1811      return err;
1812
1813   return IMGTOOLERR_SUCCESS;
1814}
1815
1816
1817
1818static imgtoolerr_t prodos_diskimage_listforks(imgtool_partition *partition, const char *path, imgtool_forkent *ents, size_t len)
1819{
1820   imgtoolerr_t err;
1821   imgtool_image *image = imgtool_partition_image(partition);
1822   prodos_dirent ent;
1823   prodos_direnum direnum;
1824   int fork_num = 0;
1825
1826   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
1827   if (err)
1828      return err;
1829
1830   if (is_dir_storagetype(ent.storage_type))
1831      return IMGTOOLERR_FILENOTFOUND;
1832
1833   /* specify data fork */
1834   ents[fork_num].type = FORK_DATA;
1835   ents[fork_num].forkname[0] = '\0';
1836   ents[fork_num].size = ent.filesize[0];
1837   fork_num++;
1838
1839   if (is_extendedfile_storagetype(ent.storage_type))
1840   {
1841      /* specify the resource fork */
1842      ents[fork_num].type = FORK_RESOURCE;
1843      strcpy(ents[fork_num].forkname, "RESOURCE_FORK");
1844      ents[fork_num].size = ent.filesize[1];
1845      fork_num++;
1846   }
1847
1848   ents[fork_num].type = FORK_END;
1849   return IMGTOOLERR_SUCCESS;
1850}
1851
1852
1853
1854static imgtoolerr_t prodos_diskimage_createdir(imgtool_partition *partition, const char *path)
1855{
1856   imgtoolerr_t err;
1857   imgtool_image *image = imgtool_partition_image(partition);
1858   prodos_dirent ent;
1859   prodos_direnum direnum;
1860
1861   err = prodos_lookup_path(image, path, CREATE_DIR, &direnum, &ent);
1862   if (err)
1863      return err;
1864
1865   /* only work on directories */
1866   if (!is_dir_storagetype(ent.storage_type))
1867      return IMGTOOLERR_FILENOTFOUND;
1868
1869   return IMGTOOLERR_SUCCESS;
1870}
1871
1872
1873
1874static imgtoolerr_t prodos_free_directory(imgtool_image *image, UINT8 *volume_bitmap, UINT16 key_pointer)
1875{
1876   imgtoolerr_t err;
1877   prodos_diskinfo *di;
1878   int i;
1879   UINT16 next_block;
1880   UINT32 offset;
1881   UINT8 buffer[BLOCK_SIZE];
1882
1883   di = get_prodos_info(image);
1884
1885   if (key_pointer != 0)
1886   {
1887      err = prodos_load_block(image, key_pointer, buffer);
1888      if (err)
1889         return err;
1890
1891      for (i = 0; i < di->dirents_per_block; i++)
1892      {
1893         offset = i * di->dirent_size + 4;
1894
1895         if (is_file_storagetype(buffer[offset]) || is_file_storagetype(buffer[offset]))
1896            return IMGTOOLERR_DIRNOTEMPTY;
1897      }
1898
1899      next_block = pick_integer_le(buffer, 2, 2);
1900
1901      err = prodos_free_directory(image, volume_bitmap, next_block);
1902      if (err)
1903         return err;
1904
1905      prodos_set_volume_bitmap_bit(volume_bitmap, key_pointer, 0);
1906   }
1907   return IMGTOOLERR_SUCCESS;
1908}
1909
1910
1911
1912static imgtoolerr_t prodos_diskimage_deletedir(imgtool_partition *partition, const char *path)
1913{
1914   imgtoolerr_t err;
1915   imgtool_image *image = imgtool_partition_image(partition);
1916   prodos_dirent ent;
1917   prodos_direnum direnum;
1918   UINT8 *volume_bitmap = NULL;
1919
1920   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
1921   if (err)
1922      goto done;
1923
1924   /* only work on directories */
1925   if (!is_dir_storagetype(ent.storage_type))
1926   {
1927      err = IMGTOOLERR_FILENOTFOUND;
1928      goto done;
1929   }
1930
1931   err = prodos_load_volume_bitmap(image, &volume_bitmap);
1932   if (err)
1933      goto done;
1934
1935   err = prodos_free_directory(image, volume_bitmap, ent.key_pointer[0]);
1936   if (err)
1937      goto done;
1938
1939   err = prodos_save_volume_bitmap(image, volume_bitmap);
1940   if (err)
1941      goto done;
1942
1943   memset(&ent, 0, sizeof(ent));
1944   err = prodos_put_dirent(image, &direnum, &ent);
1945   if (err)
1946      goto done;
1947
1948done:
1949   if (volume_bitmap)
1950      free(volume_bitmap);
1951   return IMGTOOLERR_SUCCESS;
1952}
1953
1954
1955
1956static imgtoolerr_t prodos_get_file_tree(imgtool_image *image, imgtool_chainent *chain, size_t chain_size,
1957   size_t *chain_pos, UINT16 block, UINT8 total_depth, UINT8 cur_depth)
1958{
1959   imgtoolerr_t err;
1960   prodos_diskinfo *di;
1961   int i;
1962   UINT16 sub_block;
1963   UINT8 buffer[BLOCK_SIZE];
1964
1965   if (block == 0)
1966      return IMGTOOLERR_SUCCESS;
1967   if (*chain_pos >= chain_size)
1968      return IMGTOOLERR_SUCCESS;
1969
1970   /* check bounds */
1971   di = get_prodos_info(image);
1972   if (block >= di->total_blocks)
1973      return IMGTOOLERR_CORRUPTFILE;
1974
1975   chain[*chain_pos].level = cur_depth;
1976   chain[*chain_pos].block = block;
1977   (*chain_pos)++;
1978
1979   /* must we recurse into the tree? */
1980   if (cur_depth < total_depth)
1981   {
1982      err = prodos_load_block(image, block, buffer);
1983      if (err)
1984         return err;
1985
1986      for (i = 0; i < 256; i++)
1987      {
1988         sub_block = buffer[i + 256];
1989         sub_block <<= 8;
1990         sub_block |= buffer[i + 0];
1991
1992         err = prodos_get_file_tree(image, chain, chain_size, chain_pos, sub_block, total_depth, cur_depth + 1);
1993         if (err)
1994            return err;
1995      }
1996   }
1997   return IMGTOOLERR_SUCCESS;
1998}
1999
2000
2001
2002static imgtoolerr_t prodos_diskimage_getattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, imgtool_attribute *values)
2003{
2004   imgtoolerr_t err;
2005   imgtool_image *image = imgtool_partition_image(partition);
2006   prodos_dirent ent;
2007   int i;
2008
2009   err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
2010   if (err)
2011      return err;
2012
2013   for (i = 0; attrs[i]; i++)
2014   {
2015      switch(attrs[i])
2016      {
2017         case IMGTOOLATTR_INT_MAC_TYPE:
2018            values[i].i = ent.file_type;
2019            break;
2020         case IMGTOOLATTR_INT_MAC_CREATOR:
2021            values[i].i = ent.file_creator;
2022            break;
2023         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
2024            values[i].i = ent.finder_flags;
2025            break;
2026         case IMGTOOLATTR_INT_MAC_COORDX:
2027            values[i].i = ent.coord_x;
2028            break;
2029         case IMGTOOLATTR_INT_MAC_COORDY:
2030            values[i].i = ent.coord_y;
2031            break;
2032         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
2033            values[i].i = ent.finder_folder;
2034            break;
2035         case IMGTOOLATTR_INT_MAC_ICONID:
2036            values[i].i = ent.icon_id;
2037            break;
2038         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
2039            values[i].i = ent.script_code;
2040            break;
2041         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
2042            values[i].i = ent.extended_flags;
2043            break;
2044         case IMGTOOLATTR_INT_MAC_COMMENTID:
2045            values[i].i = ent.comment_id;
2046            break;
2047         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
2048            values[i].i = ent.putaway_directory;
2049            break;
2050
2051         case IMGTOOLATTR_TIME_CREATED:
2052            values[i].t = prodos_crack_time(ent.creation_time);
2053            break;
2054         case IMGTOOLATTR_TIME_LASTMODIFIED:
2055            values[i].t = prodos_crack_time(ent.lastmodified_time);
2056            break;
2057      }
2058   }
2059
2060   return IMGTOOLERR_SUCCESS;
2061}
2062
2063
2064
2065static imgtoolerr_t prodos_diskimage_setattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, const imgtool_attribute *values)
2066{
2067   imgtoolerr_t err;
2068   imgtool_image *image = imgtool_partition_image(partition);
2069   prodos_dirent ent;
2070   prodos_direnum direnum;
2071   int i;
2072
2073   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
2074   if (err)
2075      return err;
2076
2077   for (i = 0; attrs[i]; i++)
2078   {
2079      switch(attrs[i])
2080      {
2081         case IMGTOOLATTR_INT_MAC_TYPE:
2082            ent.file_type = values[i].i;
2083            break;
2084         case IMGTOOLATTR_INT_MAC_CREATOR:
2085            ent.file_creator = values[i].i;
2086            break;
2087         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
2088            ent.finder_flags = values[i].i;
2089            break;
2090         case IMGTOOLATTR_INT_MAC_COORDX:
2091            ent.coord_x = values[i].i;
2092            break;
2093         case IMGTOOLATTR_INT_MAC_COORDY:
2094            ent.coord_y = values[i].i;
2095            break;
2096         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
2097            ent.finder_folder = values[i].i;
2098            break;
2099         case IMGTOOLATTR_INT_MAC_ICONID:
2100            ent.icon_id = values[i].i;
2101            break;
2102         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
2103            ent.script_code = values[i].i;
2104            break;
2105         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
2106            ent.extended_flags = values[i].i;
2107            break;
2108         case IMGTOOLATTR_INT_MAC_COMMENTID:
2109            ent.comment_id = values[i].i;
2110            break;
2111         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
2112            ent.putaway_directory = values[i].i;
2113            break;
2114
2115         case IMGTOOLATTR_TIME_CREATED:
2116            ent.creation_time = prodos_setup_time(values[i].t);
2117            break;
2118         case IMGTOOLATTR_TIME_LASTMODIFIED:
2119            ent.lastmodified_time = prodos_setup_time(values[i].t);
2120            break;
2121      }
2122   }
2123
2124   err = prodos_put_dirent(image, &direnum, &ent);
2125   if (err)
2126      return err;
2127
2128   return IMGTOOLERR_SUCCESS;}
2129
2130
2131
2132static imgtoolerr_t prodos_diskimage_suggesttransfer(imgtool_partition *partition, const char *path, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
2133{
2134   imgtoolerr_t err;
2135   imgtool_image *image = imgtool_partition_image(partition);
2136   prodos_dirent ent;
2137   mac_filecategory_t file_category = MAC_FILECATEGORY_DATA;
2138
2139   if (path)
2140   {
2141      err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
2142      if (err)
2143         return err;
2144
2145      file_category = is_extendedfile_storagetype(ent.storage_type)
2146         ? MAC_FILECATEGORY_FORKED : MAC_FILECATEGORY_DATA;
2147   }
2148
2149   mac_suggest_transfer(file_category, suggestions, suggestions_length);
2150   return IMGTOOLERR_SUCCESS;
2151}
2152
2153
2154
2155static imgtoolerr_t   prodos_diskimage_getchain(imgtool_partition *partition, const char *path, imgtool_chainent *chain, size_t chain_size)
2156{
2157   imgtoolerr_t err;
2158   imgtool_image *image = imgtool_partition_image(partition);
2159   prodos_dirent ent;
2160   size_t chain_pos = 0;
2161   mac_fork_t fork_num;
2162
2163   err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
2164   if (err)
2165      return err;
2166
2167   switch(ent.storage_type & 0xF0)
2168   {
2169      case 0x10:
2170      case 0x20:
2171      case 0x30:
2172         /* normal ProDOS file */
2173         err = prodos_get_file_tree(image, chain, chain_size, &chain_pos,
2174            ent.key_pointer[0], ent.depth[0] - 1, 0);
2175         if (err)
2176            return err;
2177         break;
2178     
2179      case 0x50:
2180         /* extended ProDOS file */
2181         chain[chain_pos].level = 0;
2182         chain[chain_pos].block = ent.extkey_pointer;
2183         chain_pos++;
2184
2185         for (fork_num = 0; fork_num <= 1; fork_num++)
2186         {
2187            if (ent.key_pointer[fork_num])
2188            {
2189               err = prodos_get_file_tree(image, chain, chain_size, &chain_pos,
2190                  ent.key_pointer[fork_num], ent.depth[fork_num] - 1, 1);
2191               if (err)
2192                  return err;
2193            }
2194         }
2195         break;
2196
2197      case 0xE0:
2198         /* directory */
2199         return IMGTOOLERR_UNIMPLEMENTED;
2200
2201      default:
2202         return IMGTOOLERR_UNEXPECTED;
2203   }
2204
2205   return IMGTOOLERR_SUCCESS;
2206}
2207
2208
2209
2210static void generic_prodos_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2211{
2212   switch(state)
2213   {
2214      /* --- the following bits of info are returned as 64-bit signed integers --- */
2215      case IMGTOOLINFO_INT_INITIAL_PATH_SEPARATOR:      info->i = 1; break;
2216      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
2217      case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME:      info->i = 1; break;
2218      case IMGTOOLINFO_INT_SUPPORTS_LASTMODIFIED_TIME:   info->i = 1; break;
2219      case IMGTOOLINFO_INT_WRITING_UNTESTED:            info->i = 1; break;
2220      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(prodos_diskinfo); break;
2221      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(prodos_direnum); break;
2222      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = '/'; break;
2223
2224      /* --- the following bits of info are returned as NULL-terminated strings --- */
2225      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "ProDOS format"); break;
2226      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
2227      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
2228
2229      /* --- the following bits of info are returned as pointers to data or functions --- */
2230      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
2231      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = prodos_diskimage_beginenum; break;
2232      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = prodos_diskimage_nextenum; break;
2233      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = prodos_diskimage_freespace; break;
2234      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = prodos_diskimage_readfile; break;
2235      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = prodos_diskimage_writefile; break;
2236      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = prodos_diskimage_deletefile; break;
2237      case IMGTOOLINFO_PTR_LIST_FORKS:               info->list_forks = prodos_diskimage_listforks; break;
2238      case IMGTOOLINFO_PTR_CREATE_DIR:               info->create_dir = prodos_diskimage_createdir; break;
2239      case IMGTOOLINFO_PTR_DELETE_DIR:               info->delete_dir = prodos_diskimage_deletedir; break;
2240      case IMGTOOLINFO_PTR_GET_ATTRS:                  info->get_attrs = prodos_diskimage_getattrs; break;
2241      case IMGTOOLINFO_PTR_SET_ATTRS:                  info->set_attrs = prodos_diskimage_setattrs; break;
2242      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = prodos_diskimage_suggesttransfer; break;
2243      case IMGTOOLINFO_PTR_GET_CHAIN:                  info->get_chain = prodos_diskimage_getchain; break;
2244   }
2245}
2246
2247
2248
2249void prodos_525_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2250{
2251   switch(state)
2252   {
2253      /* --- the following bits of info are returned as NULL-terminated strings --- */
2254      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "prodos_525"); break;
2255
2256      /* --- the following bits of info are returned as pointers to data or functions --- */
2257      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = prodos_diskimage_create_525; break;
2258      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = prodos_diskimage_open_525; break;
2259      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_apple2; break;
2260
2261      default:                                 generic_prodos_get_info(imgclass, state, info); break;
2262   }
2263}
2264
2265
2266
2267void prodos_35_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2268{
2269   switch(state)
2270   {
2271      /* --- the following bits of info are returned as NULL-terminated strings --- */
2272      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "prodos_35"); break;
2273
2274      /* --- the following bits of info are returned as pointers to data or functions --- */
2275      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = prodos_diskimage_create_35; break;
2276      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = prodos_diskimage_open_35; break;
2277      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_apple35_iigs; break;
2278
2279      default:                                 generic_prodos_get_info(imgclass, state, info); break;
2280   }
2281}
src/mess/tools/imgtool/msx_dsk.c
r1339r1340
1/*
2 * msx_dsk.c : converts .ddi/.img/.msx/multidisk disk images to .dsk image
3 *
4 * Sean Young 2001
5 */
6
7/*
8 * .msx files are a certain type of disk dumps. They always seem to be
9 * double sided 720kB ones. There are no extra headers, but the order of
10 * the sectors is all messed up. This little program should put that
11 * straight. :)
12 *
13 * The structure is as follows: the first 9 sectors (=0x1200 bytes) of the
14 * first side, then the first 9 sectors of the other side, the next 9
15 * sectors of the first site, the next 9 sectors of the other side.. etc.
16 *
17 * These weird .msx files are found at: ftp://jazz.snu.ac.kr/pub/msx/
18 */
19
20/*
21 * .ddi DiskDupe images are always double sided 720kB images (at least in the
22 * MSX world). There is a header of 0x1200 bytes (in the version known to the
23 * MSX world; this is version is 5.12 -- and probably others). This format
24 * is used by the CompuJunks MSX2 emulator (MSX2EMUL).
25 *
26 * The exact format of the header is unknown to me. However, this does not
27 * seem to be important; the last 720kB is a complete continuous dump of
28 * the disk.
29 */
30
31/*
32 * .img files have the following format: first a one byte header, which
33 * is 1 (01h) for singled sided 360kB images, and 2 (02h) for double sided
34 * 720kB images. These files can be found at ftp://ftp.funet.fi/pub/msx/
35 */
36
37/*
38 * .dsk multidisks are used by fmsx-dos 1.6. These files are always double
39 * sided 3.5" disks (720kB), simply appended to one another.
40 */
41
42#include <assert.h>
43#include "osdepend.h"
44#include "imgtoolx.h"
45#include "utils.h"
46
47
48typedef struct {
49   imgtool_image         base;
50   char         *file_name;
51   imgtool_stream          *file_handle;
52   int          size, format, disks;
53   } DSK_IMAGE;
54
55typedef struct
56   {
57   imgtool_directory    base;
58   DSK_IMAGE   *image;
59   int         index;
60   } DSK_ITERATOR;
61
62static int msx_dsk_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
63static void msx_dsk_image_exit(imgtool_image *img);
64static int msx_dsk_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
65static int msx_dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
66static void msx_dsk_image_closeenum(imgtool_directory *enumeration);
67static int msx_dsk_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
68
69IMAGEMODULE(
70   msx_img,
71   "MSX .img diskimage",            /* human readable name */
72   "img",                        /* file extension */
73   NULL,                        /* crcfile */
74   NULL,                        /* crc system name */
75   NULL,                        /* eoln */
76   0,                           /* flags */
77   msx_dsk_image_init,               /* init function */
78   msx_dsk_image_exit,               /* exit function */
79   NULL,                        /* info function */
80   msx_dsk_image_beginenum,         /* begin enumeration */
81   msx_dsk_image_nextenum,            /* enumerate next */
82   msx_dsk_image_closeenum,         /* close enumeration */
83   NULL,                        /* free space on image */
84   msx_dsk_image_readfile,            /* read file */
85   NULL,                        /* write file */
86   NULL,                        /* delete file */
87   NULL,                        /* create image */
88   NULL,                        /* read sector */
89   NULL,                        /* write sector */
90   NULL,                        /* file options */
91   NULL                        /* create options */
92)
93
94IMAGEMODULE(
95   msx_ddi,
96   "MSX DiskDupe .ddi diskimage",      /* human readable name */
97   "ddi",                        /* file extension */
98   NULL,                        /* crcfile */
99   NULL,                        /* crc system name */
100   NULL,                        /* eoln */
101   0,                           /* flags */
102   msx_dsk_image_init,               /* init function */
103   msx_dsk_image_exit,               /* exit function */
104   NULL,                        /* info function */
105   msx_dsk_image_beginenum,         /* begin enumeration */
106   msx_dsk_image_nextenum,            /* enumerate next */
107   msx_dsk_image_closeenum,         /* close enumeration */
108   NULL,                        /* free space on image */
109   msx_dsk_image_readfile,            /* read file */
110   NULL,                        /* write file */
111   NULL,                        /* delete file */
112   NULL,                        /* create image */
113   NULL,                        /* read sector */
114   NULL,                        /* write sector */
115   NULL,                        /* file options */
116   NULL                        /* create options */
117)
118
119IMAGEMODULE(
120   msx_msx,
121   "MSX .msx diskimage",            /* human readable name */
122   "ddi",                        /* file extension */
123   NULL,                        /* crcfile */
124   NULL,                        /* crc system name */
125   NULL,                        /* eoln */
126   0,                           /* flags */
127   msx_dsk_image_init,               /* init function */
128   msx_dsk_image_exit,               /* exit function */
129   NULL,                        /* info function */
130   msx_dsk_image_beginenum,         /* begin enumeration */
131   msx_dsk_image_nextenum,            /* enumerate next */
132   msx_dsk_image_closeenum,         /* close enumeration */
133   NULL,                        /* free space on image */
134   msx_dsk_image_readfile,            /* read file */
135   NULL,                        /* write file */
136   NULL,                        /* delete file */
137   NULL,                        /* create image */
138   NULL,                        /* read sector */
139   NULL,                        /* write sector */
140   NULL,                        /* file options */
141   NULL                        /* create options */
142)
143
144IMAGEMODULE(
145   msx_mul,
146   "MSX multi disk image",            /* human readable name */
147   "dsk",                        /* file extension */
148   NULL,                        /* crcfile */
149   NULL,                        /* crc system name */
150   NULL,                        /* eoln */
151   0,                           /* flags */
152   msx_dsk_image_init,               /* init function */
153   msx_dsk_image_exit,               /* exit function */
154   NULL,                        /* info function */
155   msx_dsk_image_beginenum,         /* begin enumeration */
156   msx_dsk_image_nextenum,            /* enumerate next */
157   msx_dsk_image_closeenum,         /* close enumeration */
158   NULL,                        /* free space on image */
159   msx_dsk_image_readfile,            /* read file */
160   NULL,                        /* write file */
161   NULL,                        /* delete file */
162   NULL,                        /* create image */
163   NULL,                        /* read sector */
164   NULL,                        /* write sector */
165   NULL,                        /* file options */
166   NULL                        /* create options */
167)
168
169#define    FORMAT_IMG      (0)
170#define    FORMAT_DDI      (1)
171#define    FORMAT_MSX      (2)
172#define    FORMAT_MULTI   (3)
173
174static int msx_dsk_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
175{
176   DSK_IMAGE *image;
177   int size, disks, correct, format;
178    UINT8 header;
179
180   size = stream_size (f);
181   if (size < (360*1024) )
182      return IMGTOOLERR_MODULENOTFOUND;
183   
184   disks = 1;
185
186   correct = 0;
187
188   if (!strcmp(mod->name, "msx_img"))
189   {
190      format = FORMAT_IMG;
191      if (1 != stream_read (f, &header, 1) )
192         return IMGTOOLERR_READERROR;
193
194      if ( (size == (720*1024+1) ) && (header == 2) )
195         {
196         correct = 1;
197         size--;
198         }
199      if ( (size == (360*1024+1) ) && (header == 1) )
200         {
201         correct = 1;
202         size--;
203         }
204   }
205   else if (!strcmp(mod->name, "msx_msx"))
206   {
207      format = FORMAT_MSX;
208      if (size == (720*1024) )
209         correct = 1;
210   }
211   else if (!strcmp(mod->name, "msx_ddi"))
212   {
213      format = FORMAT_DDI;
214      if (size == (720*1024+0x1200) )
215         {
216         size -= 0x1200;
217         correct = 1;
218         }
219   }
220   else if (!strcmp(mod->name, "msx_mul"))
221   {
222      format = FORMAT_MULTI;
223      if ( (size > 720*1024) && !(size % (720*1024) ) )
224         {
225         disks = size / (720*1024);
226         correct = 1;
227         size = 720*1024;
228         }
229   }
230   else
231   {
232      assert(0);
233      return IMGTOOLERR_UNEXPECTED;
234   }
235   
236   if (!correct) return IMGTOOLERR_MODULENOTFOUND;
237
238   image = (DSK_IMAGE*)malloc (sizeof (DSK_IMAGE) );
239   if (!image) return IMGTOOLERR_OUTOFMEMORY;
240
241   *outimg = (imgtool_image*)image;
242
243   memset(image, 0, sizeof(DSK_IMAGE));
244   image->base.module = mod;
245   image->file_handle = f;
246   image->size = size;
247   image->format = format;
248   image->file_name = NULL;
249   image->disks = disks;
250
251   return 0;
252   }
253
254static void msx_dsk_image_exit(imgtool_image *img)
255   {
256   DSK_IMAGE *image=(DSK_IMAGE*)img;
257   stream_close(image->file_handle);
258   if (image->file_name) free(image->file_name);
259   free(image);
260   }
261
262static int msx_dsk_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
263   {
264   DSK_IMAGE *image=(DSK_IMAGE*)img;
265   DSK_ITERATOR *iter;
266
267   iter=*(DSK_ITERATOR**)outenum = (DSK_ITERATOR*) malloc(sizeof(DSK_ITERATOR));
268   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
269
270   iter->base.module = image->base.module;
271   iter->image=image;
272   iter->index = 1;
273
274   return 0;
275   }
276
277static int msx_dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
278   {
279   DSK_ITERATOR *iter=(DSK_ITERATOR*)enumeration;
280
281   ent->eof = (iter->index > iter->image->disks);
282   if (!ent->eof)
283      {
284      if (iter->image->file_name)
285         strcpy (ent->fname, iter->image->file_name);
286      else
287         {
288         if (iter->image->disks ==  1)
289            strcpy (ent->fname, "msx.dsk");
290         else
291            sprintf (ent->fname, "msx-%d.dsk", iter->index);
292         }
293
294      ent->corrupt=0;
295      ent->filesize = iter->image->size;
296
297      iter->index++;
298      }
299
300   return 0;
301   }
302
303static void msx_dsk_image_closeenum(imgtool_directory *enumeration)
304   {
305   free(enumeration);
306   }
307
308static int msx_dsk_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
309   {
310   DSK_IMAGE *image=(DSK_IMAGE*)img;
311   UINT8   buf[0x1200];
312   int    i, offset, n1, n2, disks = 0;
313
314   /*  check file name */
315   switch (image->format)
316      {
317      case FORMAT_IMG:
318      case FORMAT_DDI:
319      case FORMAT_MSX:
320         if (strcmpi (fname, "msx.dsk") )
321            return IMGTOOLERR_MODULENOTFOUND;
322         break;
323      case FORMAT_MULTI:
324         if (strncmpi (fname, "msx-", 4) )
325            return IMGTOOLERR_MODULENOTFOUND;
326         offset = 4; disks = 0;
327         while ( (fname[offset] >= '0') || (fname[offset] <= '9') )
328            disks = disks * 10 + (fname[offset++] - '0');
329
330         if (mame_stricmp (fname + offset, ".dsk") )
331            return IMGTOOLERR_MODULENOTFOUND;
332
333         if ( (disks < 1) || (disks > image->disks) )
334            return IMGTOOLERR_MODULENOTFOUND;
335
336         break;
337      }
338
339   /* copy the file */
340   switch (image->format)
341      {
342      case FORMAT_MSX:
343         i = 80; n1 = 0; n2 = 80;
344         while (i--)
345            {
346            stream_seek (image->file_handle, n1++ * 0x1200, SEEK_SET);
347            if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
348               return IMGTOOLERR_READERROR;
349
350            if (0x1200 != stream_write (destf, buf, 0x1200) )
351               return IMGTOOLERR_WRITEERROR;
352
353            stream_seek (image->file_handle, n2++ * 0x1200, SEEK_SET);
354            if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
355               return IMGTOOLERR_READERROR;
356
357            if (0x1200 != stream_write (destf, buf, 0x1200) )
358               return IMGTOOLERR_WRITEERROR;
359            }
360
361         return 0;
362      case FORMAT_IMG:
363         offset = 1; i = (image->size / 0x1200);
364         break;
365      case FORMAT_DDI:
366         offset = 0x1200; i = 160;
367         break;
368      case FORMAT_MULTI:   /* multi disk */
369         i = 160; offset = 720*1024 * (disks - 1);
370         break;
371      default:
372         return IMGTOOLERR_UNEXPECTED;
373      }
374
375   stream_seek (image->file_handle, offset, SEEK_SET);
376
377   while (i--)
378      {
379      if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
380         return IMGTOOLERR_READERROR;
381
382      if (0x1200 != stream_write (destf, buf, 0x1200) )
383         return IMGTOOLERR_WRITEERROR;
384      }
385
386   return 0;
387   }
388
src/mess/tools/imgtool/fat.c
r1339r1340
1/****************************************************************************
2
3   fat.c
4
5   PC FAT disk images
6
7*****************************************************************************
8
9  Master boot record format:
10
11  Offset  Length  Description
12  ------  ------  -----------
13       0     446  Boot machine code
14     446      16  Partion #1 info
15     462      16  Partion #2 info
16     478      16  Partion #3 info
17     494      16  Partion #4 info
18    510       2  Magic bytes (0x55 0xAA)
19
20
21  Partition info format:
22
23  Offset  Length  Description
24  ------  ------  -----------
25       0       1  Active byte (0x80=active 0x00=inactive)
26      1       1  Starting head
27      2       1  Starting sector (bits 5-0) and high bits of starting track (bits 6-5)
28      3       1  Low bits of starting track
29      4       1  Partition type:
30                   0x00      Unused
31                  0x?1      FAT12   (0-15 MB)
32                  0x?2      XENIX
33                  0x?4      FAT16   (16-32 MB)
34                  0x?6      FAT16`   (32 MB-2 GB)
35                  0x?7      HPFS or NTFS
36                  0x?A      Boot Manager
37                  0x?B      FAT32   (512 MB-2 TB)
38                  0x?C      FAT32   (512 MB-2 TB LBA)
39                  0x1?      OS/2 Boot manager/Win95 hidden
40                  0xC?      DR-DOS secured partition
41                  0xD?      Multiuser DOS secured partition
42                  0xE?      SpeedStor extended partition
43      5       1  Ending head
44      6       1  Ending sector (bits 5-0) and high bits of ending track (bits 6-5)
45      7       1  Low bits of ending track
46      8       4  Sector index of beginning of partition
47     12       4  Total sectors in partition
48
49
50  Boot sector format:
51
52  Offset  Length  Description
53  ------  ------  -----------
54       0       3  Jump instruction (to skip over header on boot)
55      3       8  OEM Name
56      11       2  Bytes per sector
57     13       1  Sectors per cluster
58     14       2  Reserved sector count (including boot sector)
59     16       1  Number of FATs (file allocation tables)
60     17       2  Number of root directory entries
61     19       2  Total sectors (bits 0-15)
62     21       1  Media descriptor
63     22       2  Sectors per FAT
64     24       2  Sectors per track
65     26       2  Number of heads
66     28       4  Hidden sectors
67     32       4  Total sectors (bits 16-47)
68     36       1  Physical drive number
69      37       1  Current head
70     38       1  Signature
71     39       4  ID
72     43      11  Volume Label
73     54       8  FAT file system type
74     62     448  Boot machine code
75    510       2  Magic bytes (0x55 0xAA)
76
77  For more information:
78   http://support.microsoft.com/kb/q140418/
79
80
81  Directory Entry Format:
82
83  Offset  Length  Description
84  ------  ------  -----------
85       0       8  DOS File Name (padded with spaces)
86      8       3  DOS File Extension (padded with spaces)
87     11       1  File Attributes
88     12       2  Unknown
89     14       4  Time of Creation
90     18       2  Last Access Time
91     20       2  EA-Index (OS/2 stuff)
92     22       4  Last Modified Time
93     26       2  First Cluster
94     28       4  File Size
95
96
97  Dates and times are stored in separate words; when together, the time is
98  first and the date is second.
99
100   Time:
101      bits 15-11      Hour
102      bits 10- 5      Minute
103      bits  4- 0      Second / 2
104
105   Date:
106      bits 15- 9      Year - 1980
107      bits  8- 5      Month
108      bits  4- 0      Day
109
110  LFN Entry Format:
111
112  Offset  Length  Description
113  ------  ------  -----------
114       0       1  Sequence Number (bit 6 is set on highest sequence)
115      1      10  Name characters (five UTF-16LE chars)
116     11       1  Attributes (always 0x0F)
117     12       1  Reserved (always 0x00)
118     13       1  Checksum of short filename entry
119     14      12  Name characters (six UTF-16LE chars)
120     26       2  Entry Cluster (always 0x00)
121     28       4  Name characters (two UTF-16LE chars)
122 
123  Valid characters in DOS file names:
124   - Upper case letters A-Z
125   - Numbers 0-9
126   - Space (though there is no way to identify a trailing space)
127   - ! # $ % & ( ) - @ ^ _ ` { } ~
128   - Characters 128-255 (though the code page is indeterminate)
129
130  For more information:
131   http://en.wikipedia.org/wiki/File_Allocation_Table
132
133****************************************************************************/
134
135#include <time.h>
136#include <ctype.h>
137
138#include "imgtool.h"
139#include "unicode.h"
140
141#define FAT_DIRENT_SIZE         32
142#define FAT_SECLEN            512
143
144#define LOG(x)
145
146typedef struct _fat_partition_info fat_partition_info;
147struct _fat_partition_info
148{
149   UINT32 fat_bits;
150   UINT32 sectors_per_cluster;
151   UINT32 cluster_size;
152   UINT32 reserved_sectors;
153   UINT32 fat_count;
154   UINT32 root_entries;
155   UINT32 sectors_per_fat;
156   UINT64 total_sectors;
157   UINT32 total_clusters;
158};
159
160typedef struct _fat_file fat_file;
161struct _fat_file
162{
163   unsigned int root : 1;
164   unsigned int directory : 1;
165   unsigned int eof : 1;
166   UINT32 index;
167   UINT32 filesize;
168   UINT32 first_cluster;
169   UINT32 parent_first_cluster;
170   UINT32 cluster;
171   UINT32 cluster_index;
172   UINT32 dirent_sector_index;
173   UINT32 dirent_sector_offset;
174};
175
176typedef struct _fat_dirent fat_dirent;
177struct _fat_dirent
178{
179   char long_filename[512];
180   char short_filename[13];
181   unsigned int directory : 1;
182   unsigned int eof : 1;
183   UINT32 filesize;
184   UINT32 first_cluster;
185   UINT32 dirent_sector_index;
186   UINT32 dirent_sector_offset;
187   time_t creation_time;
188   time_t lastmodified_time;
189};
190
191typedef struct _fat_freeentry_info fat_freeentry_info;
192struct _fat_freeentry_info
193{
194   UINT32 required_size;
195   UINT32 candidate_position;
196   UINT32 position;
197};
198
199typedef struct _fat_mediatype fat_mediatype;
200struct _fat_mediatype
201{
202   UINT8 media_descriptor;
203   UINT8 heads;
204   UINT8 tracks;
205   UINT8 sectors;
206};
207
208typedef enum
209{
210   CREATE_NONE,
211   CREATE_FILE,
212   CREATE_DIR
213} creation_policy_t;
214
215
216
217static const fat_mediatype known_media[] =
218{
219   { 0xF0, 2, 80, 36 },
220   { 0xF0, 2, 80, 18 },
221   { 0xF9, 2, 80,  9 },
222   { 0xF9, 2, 80, 15 },
223   { 0xFD, 2, 40,  9 },
224   { 0xFF, 2, 40,  8 },
225   { 0xFC, 1, 40,  9 },
226   { 0xFE, 1, 40,  8 },
227   { 0xF8, 0,  0,  0 }
228};
229
230/* boot sector code taken from FreeDOS */
231static const UINT8 boot_sector_code[] =
232{
233   0xfa, 0xfc, 0x31, 0xc0, 0x8e, 0xd8, 0xbd, 0x00, 0x7c, 0xb8, 0xe0, 0x1f,
234   0x8e, 0xc0, 0x89, 0xee, 0x89, 0xef, 0xb9, 0x00, 0x01, 0xf3, 0xa5, 0xea,
235   0x5e, 0x7c, 0xe0, 0x1f, 0x00, 0x00, 0x60, 0x00, 0x8e, 0xd8, 0x8e, 0xd0,
236   0x8d, 0x66, 0xa0, 0xfb, 0x80, 0x7e, 0x24, 0xff, 0x75, 0x03, 0x88, 0x56,
237   0x24, 0xc7, 0x46, 0xc0, 0x10, 0x00, 0xc7, 0x46, 0xc2, 0x01, 0x00, 0x8b,
238   0x76, 0x1c, 0x8b, 0x7e, 0x1e, 0x03, 0x76, 0x0e, 0x83, 0xd7, 0x00, 0x89,
239   0x76, 0xd2, 0x89, 0x7e, 0xd4, 0x8a, 0x46, 0x10, 0x98, 0xf7, 0x66, 0x16,
240   0x01, 0xc6, 0x11, 0xd7, 0x89, 0x76, 0xd6, 0x89, 0x7e, 0xd8, 0x8b, 0x5e,
241   0x0b, 0xb1, 0x05, 0xd3, 0xeb, 0x8b, 0x46, 0x11, 0x31, 0xd2, 0xf7, 0xf3,
242   0x89, 0x46, 0xd0, 0x01, 0xc6, 0x83, 0xd7, 0x00, 0x89, 0x76, 0xda, 0x89,
243   0x7e, 0xdc, 0x8b, 0x46, 0xd6, 0x8b, 0x56, 0xd8, 0x8b, 0x7e, 0xd0, 0xc4,
244   0x5e, 0x5a, 0xe8, 0xac, 0x00, 0xc4, 0x7e, 0x5a, 0xb9, 0x0b, 0x00, 0xbe,
245   0xf1, 0x7d, 0x57, 0xf3, 0xa6, 0x5f, 0x26, 0x8b, 0x45, 0x1a, 0x74, 0x0b,
246   0x83, 0xc7, 0x20, 0x26, 0x80, 0x3d, 0x00, 0x75, 0xe7, 0x72, 0x68, 0x50,
247   0xc4, 0x5e, 0x5a, 0x8b, 0x7e, 0x16, 0x8b, 0x46, 0xd2, 0x8b, 0x56, 0xd4,
248   0xe8, 0x7e, 0x00, 0x58, 0x1e, 0x07, 0x8e, 0x5e, 0x5c, 0xbf, 0x00, 0x20,
249   0xab, 0x89, 0xc6, 0x01, 0xf6, 0x01, 0xc6, 0xd1, 0xee, 0xad, 0x73, 0x04,
250   0xb1, 0x04, 0xd3, 0xe8, 0x80, 0xe4, 0x0f, 0x3d, 0xf8, 0x0f, 0x72, 0xe8,
251   0x31, 0xc0, 0xab, 0x0e, 0x1f, 0xc4, 0x5e, 0x5a, 0xbe, 0x00, 0x20, 0xad,
252   0x09, 0xc0, 0x75, 0x05, 0x88, 0xd3, 0xff, 0x6e, 0x5a, 0x48, 0x48, 0x8b,
253   0x7e, 0x0d, 0x81, 0xe7, 0xff, 0x00, 0xf7, 0xe7, 0x03, 0x46, 0xda, 0x13,
254   0x56, 0xdc, 0xe8, 0x34, 0x00, 0xeb, 0xe0, 0x5e, 0xac, 0x56, 0xb4, 0x0e,
255   0xcd, 0x10, 0x3c, 0x2e, 0x75, 0xf5, 0xc3, 0xe8, 0xf1, 0xff, 0x45, 0x72,
256   0x72, 0x6f, 0x72, 0x21, 0x20, 0x48, 0x69, 0x74, 0x20, 0x61, 0x20, 0x6b,
257   0x65, 0x79, 0x20, 0x74, 0x6f, 0x20, 0x72, 0x65, 0x62, 0x6f, 0x6f, 0x74,
258   0x2e, 0x30, 0xe4, 0xcd, 0x13, 0xcd, 0x16, 0xcd, 0x19, 0x56, 0x89, 0x46,
259   0xc8, 0x89, 0x56, 0xca, 0x8c, 0x46, 0xc6, 0x89, 0x5e, 0xc4, 0xe8, 0xbe,
260   0xff, 0x2e, 0xb4, 0x41, 0xbb, 0xaa, 0x55, 0x8a, 0x56, 0x24, 0x84, 0xd2,
261   0x74, 0x19, 0xcd, 0x13, 0x72, 0x15, 0xd1, 0xe9, 0x81, 0xdb, 0x54, 0xaa,
262   0x75, 0x0d, 0x8d, 0x76, 0xc0, 0x89, 0x5e, 0xcc, 0x89, 0x5e, 0xce, 0xb4,
263   0x42, 0xeb, 0x26, 0x8b, 0x4e, 0xc8, 0x8b, 0x56, 0xca, 0x8a, 0x46, 0x18,
264   0xf6, 0x66, 0x1a, 0x91, 0xf7, 0xf1, 0x92, 0xf6, 0x76, 0x18, 0x89, 0xd1,
265   0x88, 0xc6, 0x86, 0xe9, 0xd0, 0xc9, 0xd0, 0xc9, 0x08, 0xe1, 0x41, 0xc4,
266   0x5e, 0xc4, 0xb8, 0x01, 0x02, 0x8a, 0x56, 0x24, 0xcd, 0x13, 0x0f, 0x82,
267   0x75, 0xff, 0x8b, 0x46, 0x0b, 0xf6, 0x76, 0xc0, 0x01, 0x46, 0xc6, 0x83,
268   0x46, 0xc8, 0x01, 0x83, 0x56, 0xca, 0x00, 0x4f, 0x75, 0x98, 0x8e, 0x46,
269   0xc6, 0x5e, 0xc3, 0x4d, 0x45, 0x54, 0x41, 0x4b, 0x45, 0x52, 0x4e, 0x53,
270   0x59, 0x53, 0x00, 0x00, 0x55, 0xaa
271};
272
273static const char fat8_string[8]  = { 'F', 'A', 'T', ' ', ' ', ' ', ' ', ' ' };
274static const char fat12_string[8] = { 'F', 'A', 'T', '1', '2', ' ', ' ', ' ' };
275static const char fat16_string[8] = { 'F', 'A', 'T', '1', '6', ' ', ' ', ' ' };
276static const char fat32_string[8] = { 'F', 'A', 'T', '3', '2', ' ', ' ', ' ' };
277
278
279
280static fat_partition_info *fat_get_partition_info(imgtool_partition *partition)
281{
282   return (fat_partition_info *) imgtool_partition_extra_bytes(partition);
283}
284
285
286
287static imgtoolerr_t fat_read_sector(imgtool_partition *partition, UINT32 sector_index,
288   int offset, void *buffer, size_t buffer_len)
289{
290   const fat_partition_info *disk_info;
291   imgtoolerr_t err;
292   UINT8 data[FAT_SECLEN];
293   UINT32 block_size;
294   size_t len;
295
296   disk_info = fat_get_partition_info(partition);
297
298   /* sanity check */
299   err = imgtool_partition_get_block_size(partition, &block_size);
300   if (err)
301      return err;
302   assert(block_size == sizeof(data));
303
304   while(buffer_len > 0)
305   {
306      err = imgtool_partition_read_block(partition, sector_index++, data);
307      if (err)
308         return err;
309
310      len = MIN(buffer_len, sizeof(data) - offset);
311      memcpy(buffer, data + offset, len);
312
313      buffer = ((UINT8 *) buffer) + len;
314      buffer_len -= len;
315      offset = 0;
316   }
317   return IMGTOOLERR_SUCCESS;
318}
319
320
321
322static imgtoolerr_t fat_write_sector(imgtool_partition *partition, UINT32 sector_index,
323   int offset, const void *buffer, size_t buffer_len)
324{
325   const fat_partition_info *disk_info;
326   imgtoolerr_t err;
327   UINT8 data[FAT_SECLEN];
328   const void *write_data;
329   UINT32 block_size;
330   size_t len;
331
332   disk_info = fat_get_partition_info(partition);
333
334   /* sanity check */
335   err = imgtool_partition_get_block_size(partition, &block_size);
336   if (err)
337      return err;
338   assert(block_size == sizeof(data));
339
340   while(buffer_len > 0)
341   {
342      len = MIN(buffer_len, sizeof(data) - offset);
343
344      if ((offset != 0) || (buffer_len < sizeof(data)))
345      {
346         err = imgtool_partition_read_block(partition, sector_index, data);
347         if (err)
348            return err;
349         memcpy(data + offset, buffer, len);
350         write_data = data;
351      }
352      else
353      {
354         write_data = buffer;
355      }
356
357      err = imgtool_partition_write_block(partition, sector_index++, write_data);
358      if (err)
359         return err;
360
361      buffer = ((UINT8 *) buffer) + len;
362      buffer_len -= len;
363      offset = 0;
364   }
365   return IMGTOOLERR_SUCCESS;
366}
367
368
369#ifdef UNUSED_FUNCTION
370static imgtoolerr_t fat_clear_sector(imgtool_partition *partition, UINT32 sector_index, UINT8 data)
371{
372   char buf[FAT_SECLEN];
373   memset(buf, data, sizeof(buf));
374   return fat_write_sector(partition, sector_index, 0, buf, sizeof(buf));
375}
376#endif
377
378
379static imgtoolerr_t fat_partition_open(imgtool_partition *partition, UINT64 first_block, UINT64 block_count)
380{
381   UINT8 header[FAT_SECLEN];
382   imgtoolerr_t err;
383   fat_partition_info *info;
384   UINT32 fat_bits, total_sectors_l, total_sectors_h, sector_size;
385   UINT64 available_sectors;
386   int has_extended_bios_param_block = TRUE;
387
388   info = fat_get_partition_info(partition);
389
390   /* read the boot/root sector */
391   err = fat_read_sector(partition, 0, 0, header, sizeof(header));
392   if (err)
393      return err;
394
395   /* magic bytes present? */
396   if ((header[510] != 0x55) || (header[511] != 0xAA))
397      return IMGTOOLERR_CORRUPTIMAGE;
398
399   /* determine which type of FAT is on this disk */
400   if (!memcmp(&header[54], fat8_string, sizeof(fat8_string)))
401      fat_bits = 8;
402   else if (!memcmp(&header[54], fat12_string, sizeof(fat12_string)))
403      fat_bits = 12;
404   else if (!memcmp(&header[54], fat16_string, sizeof(fat16_string)))
405      fat_bits = 16;
406   else if (!memcmp(&header[54], fat32_string, sizeof(fat32_string)))
407      fat_bits = 32;
408   else
409   {
410      fat_bits = 8;
411      has_extended_bios_param_block = FALSE;
412   }
413   
414   info->fat_bits            = fat_bits;
415   sector_size               = pick_integer_le(header, 11, 2);
416   info->sectors_per_cluster   = pick_integer_le(header, 13, 1);
417   info->reserved_sectors      = pick_integer_le(header, 14, 2);
418   info->fat_count            = pick_integer_le(header, 16, 1);
419   info->root_entries         = pick_integer_le(header, 17, 2);
420   total_sectors_l            = pick_integer_le(header, 19, 2);
421   info->sectors_per_fat      = pick_integer_le(header, 22, 2);
422   total_sectors_h            = pick_integer_le(header, 32, 4);
423
424   if (info->sectors_per_cluster == 0)
425      return IMGTOOLERR_CORRUPTIMAGE;
426
427   info->total_sectors = total_sectors_l + (((UINT64) total_sectors_h) << 16);
428   available_sectors = info->total_sectors - info->reserved_sectors
429      - (info->sectors_per_fat * info->fat_count)
430      - (info->root_entries * FAT_DIRENT_SIZE + FAT_SECLEN - 1) / FAT_SECLEN;
431   info->total_clusters = (available_sectors + info->sectors_per_cluster - 1) / info->sectors_per_cluster;
432   info->cluster_size = FAT_SECLEN * info->sectors_per_cluster;
433
434   if (info->fat_count == 0)
435      return IMGTOOLERR_CORRUPTIMAGE;
436   if (sector_size != FAT_SECLEN)
437      return IMGTOOLERR_CORRUPTIMAGE;
438   if (info->sectors_per_fat == 0)
439      return IMGTOOLERR_CORRUPTIMAGE;
440   if (info->sectors_per_cluster == 0)
441      return IMGTOOLERR_CORRUPTIMAGE;
442   if (info->reserved_sectors == 0)
443      return IMGTOOLERR_CORRUPTIMAGE;
444   if (info->total_clusters * info->fat_bits > info->sectors_per_fat * FAT_SECLEN * 8)
445      return IMGTOOLERR_CORRUPTIMAGE;
446
447   return IMGTOOLERR_SUCCESS;
448}
449
450
451
452imgtoolerr_t fat_partition_create(imgtool_image *image, UINT64 first_block, UINT64 block_count)
453{
454   imgtoolerr_t err;
455   UINT32 heads, tracks, sectors_per_track;
456   UINT32 fat_bits, sectors_per_cluster, reserved_sectors, hidden_sectors;
457   UINT32 root_dir_count, root_dir_sectors;
458   UINT32 sectors_per_fat, fat_count, i;
459   UINT32 boot_sector_offset;
460   UINT64 total_clusters;
461   UINT8 media_descriptor;
462   const char *title;
463   const char *fat_bits_string;
464   UINT8 header[FAT_SECLEN];
465   UINT64 first_fat_entries;
466
467   /* check for limits */
468   if (block_count > U64(0xFFFFFFFFFFFF))
469      return IMGTOOLERR_PARAMTOOLARGE;
470
471   /* get the geometry */
472   err = imgtool_image_get_geometry(image, &tracks, &heads, &sectors_per_track);
473   if (err)
474      return err;
475
476   /* cap our sector count so that we only use FAT12/16 */
477   sectors_per_cluster = (block_count + 65524 - 1) / 65524;
478
479   /* compute the FAT file system type */
480   if ((block_count / sectors_per_cluster) <= 4084)
481   {
482      fat_bits = 12;
483      fat_bits_string = fat12_string;
484   }
485   else if ((block_count / sectors_per_cluster) <= 65524)
486   {
487      fat_bits = 16;
488      fat_bits_string = fat16_string;
489   }
490   else
491   {
492      fat_bits = 32;
493      fat_bits_string = fat32_string;
494   }
495
496   /* figure out media type */
497   i = 0;
498   while((known_media[i].heads > 0) && ((known_media[i].heads != heads)
499      || (known_media[i].tracks != tracks)
500      || (known_media[i].sectors != sectors_per_track)))
501   {
502      i++;
503   }
504   media_descriptor = known_media[i].media_descriptor;
505
506   /* other miscellaneous settings */
507   title = "";
508   fat_count = 2;
509   root_dir_count = 512;
510   hidden_sectors = 0;
511   reserved_sectors = 1;
512
513   /* calculated settings */
514   root_dir_sectors = (root_dir_count * FAT_DIRENT_SIZE + FAT_SECLEN - 1) / FAT_SECLEN;
515   total_clusters = (block_count - reserved_sectors - hidden_sectors - root_dir_sectors)
516      / sectors_per_cluster;
517   sectors_per_fat = (total_clusters * fat_bits + (FAT_SECLEN * 8) - 1)
518      / (FAT_SECLEN * 8);
519
520   /* prepare the header */
521   memset(header, 0, sizeof(header));
522   memcpy(&header[3], "IMGTOOL ", 8);
523   place_integer_le(header, 11, 2, FAT_SECLEN);
524   place_integer_le(header, 13, 1, sectors_per_cluster);
525   place_integer_le(header, 14, 1, reserved_sectors);
526   place_integer_le(header, 16, 1, fat_count);
527   place_integer_le(header, 17, 2, root_dir_count);
528   place_integer_le(header, 19, 2, (UINT16) (block_count >> 0));
529   place_integer_le(header, 21, 1, media_descriptor);
530   place_integer_le(header, 22, 2, sectors_per_fat);
531   place_integer_le(header, 24, 2, sectors_per_track);
532   place_integer_le(header, 26, 2, heads);
533   place_integer_le(header, 28, 4, hidden_sectors);
534   place_integer_le(header, 32, 4, (UINT32) (block_count >> 16));
535   place_integer_le(header, 36, 1, 0xFF);
536   place_integer_le(header, 38, 1, 0x28);
537   place_integer_le(header, 39, 4, imgtool_image_rand(image));
538   memcpy(&header[43], "           ", 11);
539   memcpy(&header[54], fat_bits_string, 8);
540
541   /* store boot code */
542   boot_sector_offset = sizeof(header) - sizeof(boot_sector_code);
543   if (boot_sector_offset < 62)
544      return IMGTOOLERR_UNEXPECTED;   /* sanity check */
545   if (boot_sector_offset > 510)
546      return IMGTOOLERR_UNEXPECTED;   /* sanity check */
547   memcpy(&header[boot_sector_offset], boot_sector_code, sizeof(boot_sector_code));
548
549   /* specify jump instruction */
550   if (boot_sector_offset <= 129)
551   {
552      header[0] = 0xEB;                            /* JMP rel8 */
553      header[1] = (UINT8) (boot_sector_offset - 2);       /* (offset) */
554      header[2] = 0x90;                            /* NOP */
555   }
556   else
557   {
558      header[0] = 0xE9;                            /* JMP rel16 */
559      header[1] = (UINT8) ((boot_sector_offset - 2) >> 0); /* (offset) */
560      header[2] = (UINT8) ((boot_sector_offset - 2) >> 8); /* (offset) */
561   }
562
563   err = imgtool_image_write_block(image, first_block, header);
564   if (err)
565      return err;
566
567   /* clear out file allocation table */
568   for (i = reserved_sectors; i < (reserved_sectors + sectors_per_fat * fat_count + root_dir_sectors); i++)
569   {
570      err = imgtool_image_clear_block(image, first_block + i, 0);
571      if (err)
572         return err;
573   }
574
575   /* set first two FAT entries */
576   first_fat_entries = ((UINT64) media_descriptor) | 0xFFFFFF00;
577   first_fat_entries &= (((UINT64) 1) << fat_bits) - 1;
578   first_fat_entries |= ((((UINT64) 1) << fat_bits) - 1) << fat_bits;
579   first_fat_entries = LITTLE_ENDIANIZE_INT64(first_fat_entries);
580
581   for (i = 0; i < fat_count; i++)
582   {
583      err = imgtool_image_write_block(image, first_block + 1 + (i * sectors_per_fat), &first_fat_entries);
584      if (err)
585         return err;
586   }
587
588   return IMGTOOLERR_SUCCESS;
589}
590
591
592
593static imgtoolerr_t fat_load_fat(imgtool_partition *partition, UINT8 **fat_table)
594{
595   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
596   const fat_partition_info *disk_info;
597   UINT8 *table;
598   UINT32 table_size;
599   UINT32 pos, len;
600   UINT32 sector_index;
601
602   disk_info = fat_get_partition_info(partition);
603
604   table_size = disk_info->sectors_per_fat * disk_info->fat_count * FAT_SECLEN;
605
606   /* allocate the table with extra bytes, in case we "overextend" our reads */
607   table = malloc(table_size + sizeof(UINT64));
608   if (!table)
609   {
610      err = IMGTOOLERR_OUTOFMEMORY;
611      goto done;
612   }
613   memset(table, 0, table_size + sizeof(UINT64));
614
615   pos = 0;
616   sector_index = disk_info->reserved_sectors;
617
618   while(pos < table_size)
619   {
620      len = MIN(table_size - pos, FAT_SECLEN);
621
622      err = fat_read_sector(partition, sector_index++, 0, &table[pos], len);
623      if (err)
624         goto done;
625
626      pos += FAT_SECLEN;
627   }
628
629done:
630   if (err && table)
631   {
632      free(table);
633      table = NULL;
634   }
635   *fat_table = table;
636   return err;
637}
638
639
640
641static imgtoolerr_t fat_save_fat(imgtool_partition *partition, const UINT8 *fat_table)
642{
643   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
644   const fat_partition_info *disk_info;
645   UINT32 table_size;
646   UINT32 pos, len;
647   UINT32 sector_index;
648
649   disk_info = fat_get_partition_info(partition);
650
651   table_size = disk_info->sectors_per_fat * disk_info->fat_count * FAT_SECLEN;
652
653   pos = 0;
654   sector_index = disk_info->reserved_sectors;
655
656   while(pos < table_size)
657   {
658      len = MIN(table_size - pos, FAT_SECLEN);
659
660      err = fat_write_sector(partition, sector_index++, 0, &fat_table[pos], len);
661      if (err)
662         goto done;
663
664      pos += FAT_SECLEN;
665   }
666
667done:
668   return err;
669}
670
671
672
673static UINT32 fat_get_fat_entry(imgtool_partition *partition, const UINT8 *fat_table, UINT32 fat_entry)
674{
675   const fat_partition_info *disk_info;
676   UINT64 entry;
677   UINT32 bit_index, i;
678   UINT32 last_entry = 0;
679   UINT32 bit_mask;
680
681   disk_info = fat_get_partition_info(partition);
682   bit_index = fat_entry * disk_info->fat_bits;
683   bit_mask = 0xFFFFFFFF >> (32 - disk_info->fat_bits);
684
685   if (fat_entry >= disk_info->total_clusters)
686   {
687      assert(0);
688      return 1;
689   }
690
691   /* make sure that the cluster is free in all fats */
692   for (i = 0; i < disk_info->fat_count; i++)
693   {
694      memcpy(&entry, fat_table + (i * FAT_SECLEN
695         * disk_info->sectors_per_fat) + (bit_index / 8), sizeof(entry));
696
697      /* we've extracted the bytes; we now need to normalize it */
698      entry = LITTLE_ENDIANIZE_INT64(entry);
699      entry >>= bit_index % 8;
700      entry &= bit_mask;
701
702      if (i == 0)
703         last_entry = (UINT32) entry;
704      else if (last_entry != (UINT32) entry)
705         return 1;   /* if the FATs disagree; mark this as reserved */
706   }
707   
708   /* normalize special clusters */
709   if (last_entry >= (0xFFFFFFF0 & bit_mask))
710   {
711      last_entry |= 0xFFFFFFF0;
712      if (last_entry >= 0xFFFFFFF8)
713         last_entry = 0xFFFFFFFF;
714   }
715   return last_entry;
716}
717
718
719
720static void fat_set_fat_entry(imgtool_partition *partition, UINT8 *fat_table, UINT32 fat_entry, UINT32 value)
721{
722   const fat_partition_info *disk_info;
723   UINT64 entry;
724   UINT32 bit_index, i;
725
726   disk_info = fat_get_partition_info(partition);
727   bit_index = fat_entry * disk_info->fat_bits;
728   value &= 0xFFFFFFFF >> (32 - disk_info->fat_bits);
729
730   for (i = 0; i < disk_info->fat_count; i++)
731   {
732      memcpy(&entry, fat_table + (i * FAT_SECLEN
733         * disk_info->sectors_per_fat) + (bit_index / 8), sizeof(entry));
734
735      entry = LITTLE_ENDIANIZE_INT64(entry);
736      entry &= (~((UINT64) 0xFFFFFFFF >> (32 - disk_info->fat_bits)) << (bit_index % 8)) | ((1 << (bit_index % 8)) - 1);
737      entry |= ((UINT64) value) << (bit_index % 8);
738      entry = LITTLE_ENDIANIZE_INT64(entry);
739
740      memcpy(fat_table + (i * FAT_SECLEN
741         * disk_info->sectors_per_fat) + (bit_index / 8), &entry, sizeof(entry));
742   }
743}
744
745
746
747static void fat_debug_integrity_check(imgtool_partition *partition, const UINT8 *fat_table, const fat_file *file)
748{
749#ifdef MAME_DEBUG
750   /* debug function to test the integrity of a file */
751   UINT32 cluster;
752   const fat_partition_info *disk_info;
753
754   disk_info = fat_get_partition_info(partition);
755   cluster = file->first_cluster ? file->first_cluster : 0xFFFFFFFF;
756
757   if (!file->root)
758   {
759      while(cluster != 0xFFFFFFFF)
760      {
761         assert((cluster >= 2) && (cluster < disk_info->total_clusters));
762         cluster = fat_get_fat_entry(partition, fat_table, cluster);
763      }
764   }
765#endif
766}
767
768
769
770static imgtoolerr_t fat_seek_file(imgtool_partition *partition, fat_file *file, UINT32 pos)
771{
772   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
773   const fat_partition_info *disk_info;
774   UINT32 new_cluster;
775   UINT8 *fat_table = NULL;
776
777   disk_info = fat_get_partition_info(partition);
778
779   /* can't seek past end of file */
780   if (!file->directory && (pos > file->filesize))
781      pos = file->filesize;
782
783   if (file->first_cluster == 0)
784   {
785      /* special case; the root directory */
786      file->index = pos;
787   }
788   else
789   {
790      /* first, we need to check to see if we have to go back to the beginning */
791      if (pos < file->index)
792      {
793         file->cluster = file->first_cluster;
794         file->cluster_index = 0;
795         file->eof = 0;
796      }
797
798      /* skip ahead clusters */
799      while((file->cluster_index + disk_info->cluster_size) <= pos)
800      {
801         if (!fat_table)
802         {
803            err = fat_load_fat(partition, &fat_table);
804            if (err)
805               goto done;
806         }
807
808         new_cluster = fat_get_fat_entry(partition, fat_table, file->cluster);
809
810         file->cluster = new_cluster;
811         file->cluster_index += disk_info->cluster_size;
812
813         /* are we at the end of the file? */
814         if (new_cluster == 0xFFFFFFFF)
815         {
816            pos = file->cluster_index;
817            file->eof = 1;
818         }
819      }
820      file->index = pos;
821   }
822
823done:
824   if (fat_table)
825      free(fat_table);
826   return err;
827}
828
829
830
831static UINT32 fat_get_filepos_sector_index(imgtool_partition *partition, fat_file *file)
832{
833   UINT32 sector_index;
834   const fat_partition_info *disk_info;
835
836   disk_info = fat_get_partition_info(partition);
837
838   sector_index = disk_info->reserved_sectors + (disk_info->sectors_per_fat * disk_info->fat_count);
839   if (file->root)
840   {
841      /* special case for the root file */
842      sector_index += file->index / FAT_SECLEN;
843   }
844   else
845   {
846      /* cluster out of range? */
847      if ((file->cluster < 2) || (file->cluster >= disk_info->total_clusters))
848         return 0;
849
850      sector_index += (disk_info->root_entries * FAT_DIRENT_SIZE + FAT_SECLEN - 1) / FAT_SECLEN;
851      sector_index += (file->cluster - 2) * disk_info->sectors_per_cluster;
852      sector_index += (file->index / FAT_SECLEN) % disk_info->sectors_per_cluster;
853   }
854   return sector_index;
855}
856
857
858
859static imgtoolerr_t fat_corrupt_file_error(const fat_file *file)
860{
861   imgtoolerr_t err;
862   if (file->root)
863      err = IMGTOOLERR_CORRUPTIMAGE;
864   else if (file->directory)
865      err = IMGTOOLERR_CORRUPTDIR;
866   else
867      err = IMGTOOLERR_CORRUPTFILE;
868   return err;
869}
870
871
872
873static imgtoolerr_t fat_readwrite_file(imgtool_partition *partition, fat_file *file,
874   void *buffer, size_t buffer_len, size_t *bytes_read, int read_or_write)
875{
876   imgtoolerr_t err;
877   const fat_partition_info *disk_info;
878   UINT32 sector_index;
879   int offset;
880   size_t len;
881
882   disk_info = fat_get_partition_info(partition);
883   if (bytes_read)
884      *bytes_read = 0;
885   if (!file->directory)
886      buffer_len = MIN(buffer_len, file->filesize - file->index);
887
888   while(!file->eof && (buffer_len > 0))
889   {
890      sector_index = fat_get_filepos_sector_index(partition, file);
891      if (sector_index == 0)
892         return fat_corrupt_file_error(file);
893
894      offset = file->index % FAT_SECLEN;
895      len = MIN(buffer_len, FAT_SECLEN - offset);
896
897      /* read or write the data from the disk */
898      if (read_or_write)
899         err = fat_write_sector(partition, sector_index, offset, buffer, len);
900      else
901         err = fat_read_sector(partition, sector_index, offset, buffer, len);
902      if (err)
903         return err;
904
905      /* and move the file pointer ahead */
906      err = fat_seek_file(partition, file, file->index + len);
907      if (err)
908         return err;
909
910      buffer = ((UINT8 *) buffer) + len;
911      buffer_len -= len;
912      if (bytes_read)
913         *bytes_read += len;
914   }
915   return IMGTOOLERR_SUCCESS;
916}
917
918
919
920static imgtoolerr_t fat_read_file(imgtool_partition *partition, fat_file *file,
921   void *buffer, size_t buffer_len, size_t *bytes_read)
922{
923   return fat_readwrite_file(partition, file, buffer, buffer_len, bytes_read, 0);
924}
925
926
927
928static imgtoolerr_t fat_write_file(imgtool_partition *partition, fat_file *file,
929   const void *buffer, size_t buffer_len, size_t *bytes_read)
930{
931   return fat_readwrite_file(partition, file, (void *) buffer, buffer_len, bytes_read, 1);
932}
933
934
935
936static UINT32 fat_allocate_cluster(imgtool_partition *partition, UINT8 *fat_table)
937{
938   const fat_partition_info *disk_info;
939   UINT32 i, val;
940
941   disk_info = fat_get_partition_info(partition);
942
943   for (i = 2; i < disk_info->total_clusters; i++)
944   {
945      val = fat_get_fat_entry(partition, fat_table, i);
946      if (val == 0)
947      {
948         fat_set_fat_entry(partition, fat_table, i, 1);
949         return i;
950      }
951   }
952   return 0;
953}
954
955
956
957/* sets the size of a file; ~0 means 'delete' */
958static imgtoolerr_t fat_set_file_size(imgtool_partition *partition, fat_file *file,
959   UINT32 new_size)
960{
961   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
962   const fat_partition_info *disk_info;
963   UINT32 new_cluster_count;
964   UINT32 old_cluster_count;
965   UINT32 cluster, write_cluster, last_cluster, new_pos, i;
966   UINT8 *fat_table = NULL;
967   UINT8 dirent[32];
968   size_t clear_size;
969   void *clear_buffer = NULL;
970   int delete_file = FALSE;
971   int rest_free = FALSE;
972
973   disk_info = fat_get_partition_info(partition);
974
975   LOG(("fat_set_file_size(): file->first_cluster=%d new_size=0x%08x\n", file->first_cluster, new_size));
976
977   /* special case */
978   if (new_size == ~0)
979   {
980      delete_file = TRUE;
981      new_size = 0;
982   }
983   
984   /* if this is the trivial case (not changing the size), succeed */
985   if (!delete_file && (file->filesize == new_size))
986   {
987      err = IMGTOOLERR_SUCCESS;
988      goto done;
989   }
990
991   /* what is the new position? */
992   new_pos = MIN(file->index, new_size);
993
994   if (file->root)
995   {
996      /* this is the root directory; this is a special case */
997      if (new_size > (disk_info->root_entries * FAT_DIRENT_SIZE))
998      {
999         err = IMGTOOLERR_NOSPACE;
1000         goto done;
1001      }
1002   }
1003   else
1004   {
1005      old_cluster_count = (file->filesize + disk_info->cluster_size - 1) / disk_info->cluster_size;
1006      new_cluster_count = (new_size + disk_info->cluster_size - 1) / disk_info->cluster_size;
1007      cluster = 0;
1008
1009      /* load the dirent */
1010      err = fat_read_sector(partition, file->dirent_sector_index, file->dirent_sector_offset, dirent, sizeof(dirent));
1011      if (err)
1012         goto done;
1013
1014      /* need to load the FAT whether we are growing or shrinking the file */
1015      if (old_cluster_count != new_cluster_count)
1016      {
1017         err = fat_load_fat(partition, &fat_table);
1018         if (err)
1019            goto done;
1020
1021         cluster = 0;
1022         i = 0;
1023         do
1024         {
1025            last_cluster = cluster;
1026            write_cluster = 0;
1027
1028            /* identify the next cluster */
1029            if (cluster != 0)
1030               cluster = fat_get_fat_entry(partition, fat_table, cluster);
1031            else
1032               cluster = file->first_cluster ? file->first_cluster : 0xFFFFFFFF;
1033
1034            /* do we need to grow the file by a cluster? */
1035            if (i < new_cluster_count && ((cluster < 2) || (cluster >= disk_info->total_clusters)))
1036            {
1037               /* grow this file by a cluster */
1038               cluster = fat_allocate_cluster(partition, fat_table);
1039               if (cluster == 0)
1040               {
1041                  err = IMGTOOLERR_NOSPACE;
1042                  goto done;
1043               }
1044               
1045               write_cluster = cluster;
1046            }
1047            else if (i >= new_cluster_count)
1048            {
1049               /* we are shrinking the file; we need to unlink this node */
1050               if ((cluster < 2) || (cluster >= disk_info->total_clusters))
1051                  cluster = 0xFFFFFFFF; /* ack file is corrupt! recover */
1052               write_cluster = 0xFFFFFFFF;
1053            }
1054
1055            /* write out the entry, if appropriate */
1056            if (write_cluster != 0)
1057            {
1058               /* are we tieing up loose ends? */
1059               if (rest_free && (write_cluster == 0xFFFFFFFF))
1060                  write_cluster = 0;
1061
1062               if (last_cluster == 0)
1063                  file->first_cluster = (write_cluster != 0xFFFFFFFF) ? write_cluster : 0;
1064               else
1065                  fat_set_fat_entry(partition, fat_table, last_cluster, write_cluster);
1066
1067               /* did we write the last cluster?  if so, the rest (if any) are free */
1068               if (write_cluster == 0xFFFFFFFF)
1069                  rest_free = TRUE;
1070            }
1071         }
1072         while((++i < new_cluster_count) || (cluster != 0xFFFFFFFF));
1073      }
1074
1075      /* record the new file size */
1076      place_integer_le(dirent, 26, 2, file->first_cluster);
1077      place_integer_le(dirent, 28, 4, new_size);
1078
1079      /* delete the file, if appropriate */
1080      if (delete_file)
1081         dirent[0] = 0xE5;
1082
1083      /* save the dirent */
1084      err = fat_write_sector(partition, file->dirent_sector_index, file->dirent_sector_offset, dirent, sizeof(dirent));
1085      if (err)
1086         goto done;
1087
1088      /* if we've modified the FAT, save it out */
1089      if (fat_table)
1090      {
1091         err = fat_save_fat(partition, fat_table);
1092         if (err)
1093            goto done;
1094      }
1095
1096      /* update the file structure */
1097      if (!file->directory)
1098         file->filesize = new_size;
1099      file->cluster = file->first_cluster;
1100      file->index = 0;
1101      file->cluster_index = 0;
1102      file->eof = (new_cluster_count == 0);
1103   }
1104
1105   /* special case; clear out stale bytes on non-root directories */
1106   if (file->directory && !delete_file)
1107   {
1108      if (file->root)
1109         clear_size = MIN(file->filesize - new_size, FAT_DIRENT_SIZE);
1110      else
1111         clear_size = (disk_info->cluster_size - (new_size % disk_info->cluster_size)) % disk_info->cluster_size;
1112
1113      if (clear_size > 0)
1114      {
1115         err = fat_seek_file(partition, file, new_size);
1116         if (err)
1117            goto done;
1118
1119         clear_buffer = malloc(clear_size);
1120         if (!clear_buffer)
1121         {
1122            err = IMGTOOLERR_OUTOFMEMORY;
1123            goto done;
1124         }
1125         memset(clear_buffer, '\0', clear_size);
1126
1127         err = fat_write_file(partition, file, clear_buffer, clear_size, NULL);
1128         if (err)
1129            goto done;
1130      }
1131   }
1132
1133   /* seek back to original pos */
1134   err = fat_seek_file(partition, file, new_pos);
1135   if (err)
1136      goto done;
1137
1138   if (fat_table)
1139      fat_debug_integrity_check(partition, fat_table, file);
1140
1141done:
1142   if (fat_table)
1143      free(fat_table);
1144   if (clear_buffer)
1145      free(clear_buffer);
1146   return err;
1147}
1148
1149
1150
1151static void prepend_lfn_bytes(utf16_char *lfn_buf, size_t lfn_buflen, size_t *lfn_len,
1152   const UINT8 *entry, int offset, int chars)
1153{
1154   UINT16 w;
1155   int i;
1156   size_t move_len;
1157
1158   move_len = MIN(*lfn_len + 1, lfn_buflen - chars - 1);
1159   memmove(&lfn_buf[chars], &lfn_buf[0], move_len * sizeof(*lfn_buf));
1160
1161   for (i = 0; i < chars; i++)
1162   {
1163      /* read the character */
1164      memcpy(&w, &entry[offset + i * 2], 2);
1165      w = LITTLE_ENDIANIZE_INT16(w);
1166
1167      /* append to buffer */
1168      lfn_buf[i] = (w != 0xFFFF) ? w : 0;
1169   }
1170   *lfn_len += chars;
1171}
1172
1173
1174
1175static UINT8 fat_calc_filename_checksum(const UINT8 *short_filename)
1176{
1177   UINT8 checksum;
1178   int i, j;
1179
1180   checksum = 0;
1181   for (i = 0; i < 11; i++)
1182   {
1183      j = checksum & 1;
1184      checksum >>= 1;
1185      if (j)
1186         checksum |= 0x80;
1187      checksum += short_filename[i];
1188   }
1189   return checksum;
1190}
1191
1192
1193
1194static void fat_calc_dirent_lfnchecksum(UINT8 *entry, size_t entry_len)
1195{
1196   UINT8 checksum;
1197   int i;
1198
1199   checksum = fat_calc_filename_checksum(entry + entry_len - FAT_DIRENT_SIZE);
1200
1201   for (i = 0; i < (entry_len / FAT_DIRENT_SIZE - 1); i++)
1202      entry[i * FAT_DIRENT_SIZE + 13] = checksum;
1203}
1204
1205
1206
1207static char fat_cannonicalize_sfn_char(char ch)
1208{
1209   /* return the display version of this short file name character */
1210   return tolower(ch);
1211}
1212
1213
1214
1215static void fat_cannonicalize_sfn(char *sfn, const UINT8 *sfn_bytes)
1216{
1217   /* return the display version of this short file name */
1218   int i;
1219
1220   memset(sfn, '\0', 13);
1221   memcpy(sfn, sfn_bytes, 8);
1222   rtrim(sfn);
1223   if (sfn[0] == 0x05)
1224      sfn[0] = (char) 0xE5;
1225   if ((sfn_bytes[8] != ' ') || (sfn_bytes[9] != ' ') || (sfn_bytes[10] != ' '))
1226   {
1227      strcat(sfn, ".");
1228      memcpy(sfn + strlen(sfn), &sfn_bytes[8], 3);
1229      rtrim(sfn);
1230   }
1231   for (i = 0; sfn[i]; i++)
1232      sfn[i] = fat_cannonicalize_sfn_char(sfn[i]);
1233}
1234
1235
1236
1237static time_t fat_crack_time(UINT32 fat_time)
1238{
1239   struct tm t;
1240   time_t now;
1241
1242   time(&now);
1243   t = *localtime(&now);
1244
1245   t.tm_sec   = ((fat_time >>  0) & 0x001F) * 2;
1246   t.tm_min   = ((fat_time >>  5) & 0x003F);
1247   t.tm_hour   = ((fat_time >> 11) & 0x001F);
1248   t.tm_mday   = ((fat_time >> 16) & 0x001F);
1249   t.tm_mon   = ((fat_time >> 21) & 0x000F);
1250   t.tm_year   = ((fat_time >> 25) & 0x007F) + 1980 - 1900;
1251
1252   return mktime(&t);
1253}
1254
1255
1256
1257static UINT32 fat_setup_time(time_t ansi_time)
1258{
1259   struct tm t;
1260   UINT32 result = 0;
1261
1262   t = *localtime(&ansi_time);
1263
1264   result |= (((UINT32) (t.tm_sec / 2))         & 0x001F) <<  0;
1265   result |= (((UINT32) t.tm_min)               & 0x003F) <<  5;
1266   result |= (((UINT32) t.tm_hour)               & 0x001F) << 11;
1267   result |= (((UINT32) t.tm_mday)               & 0x001F) << 16;
1268   result |= (((UINT32) t.tm_mon)               & 0x000F) << 21;
1269   result |= (((UINT32) (t.tm_year + 1900 - 1980))   & 0x007F) << 25;
1270
1271   return result;
1272}
1273
1274
1275
1276static imgtoolerr_t fat_read_dirent(imgtool_partition *partition, fat_file *file,
1277   fat_dirent *ent, fat_freeentry_info *freeent)
1278{
1279   imgtoolerr_t err;
1280   const fat_partition_info *disk_info;
1281   UINT8 entry[FAT_DIRENT_SIZE];
1282   size_t bytes_read;
1283   int i, j;
1284   unicode_char ch;
1285   utf16_char lfn_buf[512];
1286   size_t lfn_len = 0;
1287   int lfn_lastentry = 0;
1288   UINT8 lfn_checksum = 0;
1289   UINT32 entry_index, entry_sector_index, entry_sector_offset;
1290
1291   assert(file->directory);
1292   lfn_buf[0] = '\0';
1293   memset(ent, 0, sizeof(*ent));
1294   disk_info = fat_get_partition_info(partition);
1295
1296   /* The first eight bytes of a FAT directory entry is a blank padded name
1297    *
1298    * The first byte can be special:
1299    *   0x00 - entry is available and no further entry is used
1300    *   0x05 - first character is actually 0xe5
1301    *   0x2E - dot entry; either '.' or '..'
1302    *   0xE5 - entry has been erased and is available
1303    *
1304    * Byte 11 is the attributes; and 0x0F denotes a LFN entry
1305    */
1306   do
1307   {
1308      entry_index = file->index;
1309      entry_sector_index = fat_get_filepos_sector_index(partition, file);
1310      entry_sector_offset = file->index % FAT_SECLEN;
1311
1312      err = fat_read_file(partition, file, entry, sizeof(entry), &bytes_read);
1313      if (err)
1314         return err;
1315      if (bytes_read < sizeof(entry))
1316         memset(entry, 0, sizeof(entry));
1317
1318      if (entry[11] == 0x0F)
1319      {
1320         /* this is an LFN entry */
1321         if ((lfn_lastentry == 0)
1322            || ((entry[0] & 0x3F) != (lfn_lastentry - 1))
1323            || (lfn_checksum != entry[13]))
1324         {
1325            lfn_buf[0] = 0;
1326            lfn_len = 0;
1327            lfn_checksum = entry[13];
1328         }
1329         lfn_lastentry = entry[0] & 0x3F;
1330         prepend_lfn_bytes(lfn_buf, sizeof(lfn_buf) / sizeof(lfn_buf[0]),
1331            &lfn_len, entry, 28, 2);
1332         prepend_lfn_bytes(lfn_buf, sizeof(lfn_buf) / sizeof(lfn_buf[0]),
1333            &lfn_len, entry, 14, 6);
1334         prepend_lfn_bytes(lfn_buf, sizeof(lfn_buf) / sizeof(lfn_buf[0]),
1335            &lfn_len, entry,  1, 5);
1336      }
1337      else if (freeent && (freeent->position == ~0))
1338      {
1339         /* do a quick check to find out if we found space */
1340         if ((entry[0] == '\0') || (entry[0] == 0xE5))
1341         {
1342            if (freeent->candidate_position > entry_index)
1343               freeent->candidate_position = entry_index;
1344
1345            if ((entry[0] == '\0') || (freeent->candidate_position + freeent->required_size < file->index))
1346               freeent->position = freeent->candidate_position;
1347         }
1348         else
1349         {
1350            freeent->candidate_position = ~0;
1351         }
1352      }
1353   }
1354   while((entry[0] == 0x2E) || (entry[0] == 0xE5) || (entry[11] == 0x0F));
1355
1356   /* no more directory entries? */
1357   if (entry[0] == '\0')
1358   {
1359      ent->eof = 1;
1360      return IMGTOOLERR_SUCCESS;
1361   }
1362
1363   /* pick apart short filename */
1364   fat_cannonicalize_sfn(ent->short_filename, entry);
1365
1366   /* and the long filename */
1367   if (lfn_lastentry == 1)
1368   {
1369      /* only use the LFN if the checksum passes */
1370      if (lfn_checksum == fat_calc_filename_checksum(entry))
1371      {
1372         i = 0;
1373         j = 0;
1374         do
1375         {
1376            i += uchar_from_utf16(&ch, &lfn_buf[i], sizeof(lfn_buf) / sizeof(lfn_buf[0]) - i);
1377            j += utf8_from_uchar(&ent->long_filename[j], sizeof(ent->long_filename) / sizeof(ent->long_filename[0]) - j, ch);
1378         }
1379         while(ch != 0);
1380      }
1381   }
1382
1383   /* other attributes */
1384   ent->filesize            = pick_integer_le(entry, 28, 4);
1385   ent->directory            = (entry[11] & 0x10) ? 1 : 0;
1386   ent->first_cluster         = pick_integer_le(entry, 26, 2);
1387   ent->dirent_sector_index   = entry_sector_index;
1388   ent->dirent_sector_offset   = entry_sector_offset;
1389   ent->creation_time         = fat_crack_time(pick_integer_le(entry, 14, 4));
1390   ent->lastmodified_time      = fat_crack_time(pick_integer_le(entry, 22, 4));
1391   return IMGTOOLERR_SUCCESS;
1392}
1393
1394
1395
1396typedef enum
1397{
1398   SFN_SUFFICIENT,   /* name fully representable in short file name */
1399   SFN_DERIVATIVE,   /* name not fully representable in short file name, but no need to tildize */
1400   SFN_MANGLED      /* name not representable in short file name; must tildize */
1401} sfn_disposition_t;
1402
1403static imgtoolerr_t fat_construct_dirent(const char *filename, creation_policy_t create,
1404   UINT8 **entry, size_t *entry_len)
1405{
1406   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1407   UINT8 *created_entry = NULL;
1408   UINT8 *new_created_entry;
1409   UINT32 now;
1410   size_t created_entry_len = FAT_DIRENT_SIZE;
1411   size_t created_entry_pos = 0;
1412   unicode_char ch;
1413   char last_short_char = ' ';
1414   char short_char = '\0';
1415   char cannonical_short_char;
1416   utf16_char buf[UTF16_CHAR_MAX];
1417   int i, len;
1418   int sfn_pos = 0;
1419   sfn_disposition_t sfn_disposition = SFN_SUFFICIENT;
1420   int sfn_in_extension = 0;
1421
1422   /* sanity check */
1423   if (*filename == '\0')
1424   {
1425      err = IMGTOOLERR_BADFILENAME;
1426      goto done;
1427   }
1428
1429   /* construct intial entry */
1430   created_entry = (UINT8 *) malloc(FAT_DIRENT_SIZE);
1431   if (!created_entry)
1432   {
1433      err = IMGTOOLERR_OUTOFMEMORY;
1434      goto done;
1435   }
1436
1437   /* set up the basics for the new dirent */
1438   memset(created_entry +  0, ' ', 11);
1439   memset(created_entry + 12, '\0', FAT_DIRENT_SIZE - 12);
1440   created_entry[11] = (create == CREATE_DIR) ? 0x10 : 0x00;
1441   
1442   /* set up file dates in the new dirent */
1443   now = fat_setup_time(time(NULL));
1444   place_integer_le(created_entry, 14, 4, now);
1445   place_integer_le(created_entry, 18, 2, now);
1446   place_integer_le(created_entry, 22, 4, now);
1447
1448   while(*filename)
1449   {
1450      filename += uchar_from_utf8(&ch, filename, UTF8_CHAR_MAX);
1451
1452      /* append to short filename, if possible */
1453      if ((ch < 32) || (ch > 128))
1454         short_char = '\0';
1455      else if (isalnum((char) ch))
1456         short_char = toupper((char) ch);
1457      else if (strchr(".!#$%^()-@^_`{}~", (char) ch))
1458         short_char = (char) ch;
1459      else
1460         short_char = '\0';   /* illegal SFN char */
1461      cannonical_short_char = fat_cannonicalize_sfn_char((char) ch);
1462      if (!short_char || (short_char != cannonical_short_char))
1463      {
1464         if (toupper(short_char) == toupper(cannonical_short_char))
1465            sfn_disposition = MAX(sfn_disposition, SFN_DERIVATIVE);
1466         else
1467            sfn_disposition = SFN_MANGLED;
1468      }
1469
1470      /* append the short filename char */
1471      if (short_char == '.')
1472      {
1473         /* multiple extensions or trailing spaces? */
1474         if (sfn_in_extension)
1475            sfn_disposition = SFN_MANGLED;
1476         else if (last_short_char == ' ')
1477            sfn_disposition = MAX(sfn_disposition, SFN_DERIVATIVE);
1478
1479         sfn_in_extension = 1;
1480         sfn_pos = 8;
1481         created_entry[created_entry_len - FAT_DIRENT_SIZE + 8] = ' ';
1482         created_entry[created_entry_len - FAT_DIRENT_SIZE + 9] = ' ';
1483         created_entry[created_entry_len - FAT_DIRENT_SIZE + 10] = ' ';
1484      }
1485      else if (sfn_pos == (sfn_in_extension ? 11 : 8))
1486      {
1487         /* ran out of characters for short filename */
1488         sfn_disposition = SFN_MANGLED;
1489      }
1490      else if (short_char != '\0')
1491      {
1492         created_entry[created_entry_len - FAT_DIRENT_SIZE + sfn_pos++] = short_char;
1493      }
1494      last_short_char = short_char;
1495
1496
1497      /* convert to UTF-16 and add a long filename entry */
1498      len = utf16le_from_uchar(buf, UTF16_CHAR_MAX, ch);
1499      for (i = 0; i < len; i++)
1500      {
1501         switch(created_entry_pos)
1502         {
1503            case 0:
1504            case 32:
1505               /* need to grow */
1506               new_created_entry = (UINT8 *) realloc(created_entry, created_entry_len + FAT_DIRENT_SIZE);
1507               if (!new_created_entry)
1508               {
1509                  err = IMGTOOLERR_OUTOFMEMORY;
1510                  goto done;
1511               }
1512               created_entry = new_created_entry;
1513
1514               /* move existing entries forward */
1515               memmove(created_entry + 32, created_entry, created_entry_len);
1516               created_entry_len += 32;
1517
1518               /* set up this LFN */
1519               memset(created_entry, '\0', 32);
1520               memset(&created_entry[1], '\xFF', 10);
1521               memset(&created_entry[14], '\xFF', 12);
1522               memset(&created_entry[28], '\xFF', 4);
1523               created_entry[11] = 0x0F;
1524
1525               /* specify entry index */
1526               created_entry[0] = (created_entry_len / 32) - 1;
1527               if (created_entry[0] >= 0x40)
1528               {
1529                  err = IMGTOOLERR_BADFILENAME;
1530                  goto done;
1531               }
1532               created_entry_pos = 1;
1533               break;
1534
1535            case 11:
1536               created_entry_pos = 14;
1537               break;
1538
1539            case 26:
1540               created_entry_pos = 28;
1541               break;
1542         }
1543
1544         memcpy(&created_entry[created_entry_pos], &buf[i], 2);
1545         created_entry_pos += 2;
1546      }
1547   }
1548
1549   /* trailing spaces? */
1550   if (short_char == ' ')
1551      sfn_disposition = MAX(sfn_disposition, SFN_DERIVATIVE);
1552
1553   if (sfn_disposition == SFN_SUFFICIENT)
1554   {
1555      /* the short filename suffices; remove the LFN stuff */
1556      memcpy(created_entry, created_entry + created_entry_len - FAT_DIRENT_SIZE, FAT_DIRENT_SIZE);
1557      created_entry_len = FAT_DIRENT_SIZE;
1558
1559      new_created_entry = (UINT8 *) realloc(created_entry, created_entry_len);
1560      if (!new_created_entry)
1561      {
1562         err = IMGTOOLERR_OUTOFMEMORY;
1563         goto done;
1564      }
1565      created_entry = new_created_entry;
1566   }
1567   else
1568   {
1569      /* need to do finishing touches on the LFN */
1570      created_entry[0] |= 0x40;
1571
1572      /* if necessary, mangle the name */
1573      if (sfn_disposition == SFN_MANGLED)
1574      {
1575         i = 6;
1576         while((i > 0) && isspace(created_entry[created_entry_len - FAT_DIRENT_SIZE + i - 1]))
1577            i--;
1578         created_entry[created_entry_len - FAT_DIRENT_SIZE + i + 0] = '~';
1579         created_entry[created_entry_len - FAT_DIRENT_SIZE + i + 1] = '1';
1580      }
1581      fat_calc_dirent_lfnchecksum(created_entry, created_entry_len);
1582   }
1583
1584done:
1585   if (err && created_entry)
1586   {
1587      free(created_entry);
1588      created_entry = NULL;
1589   }
1590   *entry = created_entry;
1591   *entry_len = created_entry_len;
1592   return err;
1593}
1594
1595
1596
1597static void fat_bump_dirent(imgtool_partition *partition, UINT8 *entry, size_t entry_len)
1598{
1599   UINT8 *sfn_entry;
1600   int pos, digit_count, i;
1601   UINT32 digit_place, val = 0;
1602   
1603   sfn_entry = &entry[entry_len - FAT_DIRENT_SIZE];
1604
1605   digit_place = 1;
1606   for (pos = 7; (pos >= 0) && isdigit((char) sfn_entry[pos]); pos--)
1607   {
1608      val += (sfn_entry[pos] - '0') * digit_place;
1609      digit_place *= 10;
1610   }
1611   val++;
1612   pos++;
1613
1614   /* count the digits */
1615   digit_place = 1;
1616   digit_count = 1;
1617   while(val >= digit_place * 10)
1618   {
1619      digit_count++;
1620      digit_place *= 10;
1621   }
1622
1623   /* give us some more space, if necessary */
1624   while ((pos > 0) && ((pos + digit_count) > 8))
1625      pos--;
1626
1627   /* have we actually ran out of digits */
1628   if ((pos + digit_count) > 8)
1629   {
1630      /* extreme degenerate case; simply randomize the filename */
1631      for (i = 0; i < 6; i++)
1632         sfn_entry[i] = 'A' + (imgtool_partition_rand(partition) % 26);
1633      sfn_entry[6] = '~';
1634      sfn_entry[7] = '0';
1635   }
1636   else
1637   {
1638      /* write the tilde, if possible */
1639      if (pos > 0)
1640         sfn_entry[pos - 1] = '~';
1641
1642      /* write out the number */
1643      while(digit_place > 0)
1644      {
1645         sfn_entry[pos++] = (val / digit_place) + '0';
1646         val %= digit_place;
1647         digit_place /= 10;
1648      }
1649   }
1650
1651   /* since we changed the short file name, we need to recalc the checksums
1652    * in the LFN entries */
1653   fat_calc_dirent_lfnchecksum(entry, entry_len);
1654}
1655
1656
1657
1658static imgtoolerr_t fat_lookup_path(imgtool_partition *partition, const char *path,
1659   creation_policy_t create, fat_file *file)
1660{
1661   imgtoolerr_t err;
1662   const fat_partition_info *disk_info;
1663   fat_dirent ent;
1664   fat_freeentry_info freeent = { 0, };
1665   const char *next_path_part;
1666   UINT8 *created_entry = NULL;
1667   size_t created_entry_len = 0;
1668   UINT32 entry_sector_index, entry_sector_offset;
1669   UINT32 parent_first_cluster;
1670   int bumped_sfn;
1671   char sfn[13];
1672
1673   disk_info = fat_get_partition_info(partition);
1674
1675   memset(file, 0, sizeof(*file));
1676   file->root = 1;
1677   file->directory = 1;
1678   file->filesize = disk_info->root_entries * FAT_DIRENT_SIZE;
1679
1680   while(*path)
1681   {
1682      if (!file->directory)
1683      {
1684         err = IMGTOOLERR_PATHNOTFOUND;
1685         goto done;
1686      }
1687
1688      next_path_part = path + strlen(path) + 1;
1689      if (create && (*next_path_part == '\0'))
1690      {
1691         /* this is the last entry, and we are creating a file */
1692         err = fat_construct_dirent(path, create, &created_entry, &created_entry_len);
1693         if (err)
1694            goto done;
1695
1696         freeent.required_size = created_entry_len;
1697         freeent.candidate_position = ~0;
1698         freeent.position = ~0;
1699      }
1700
1701      do
1702      {
1703         err = fat_read_dirent(partition, file, &ent, created_entry ? &freeent : NULL);
1704         if (err)
1705            goto done;
1706
1707         LOG(("fat_lookup_path(): %s/%s: %d\n", ent.short_filename, ent.long_filename, ent.dirent_sector_offset));
1708      }
1709      while(!ent.eof && mame_stricmp(path, ent.short_filename) && mame_stricmp(path, ent.long_filename));
1710
1711      parent_first_cluster = file->first_cluster;
1712
1713      if (ent.eof)
1714      {
1715         /* it seems that we have reached the end of this directory */
1716         if (!created_entry)
1717         {
1718            err = IMGTOOLERR_FILENOTFOUND;
1719            goto done;
1720         }
1721
1722         if (created_entry_len > FAT_DIRENT_SIZE)
1723         {
1724            /* must ensure uniqueness of the short filename */
1725            do
1726            {
1727               /* rewind to the beginning of the directory */
1728               err = fat_seek_file(partition, file, 0);
1729               if (err)
1730                  goto done;
1731
1732               bumped_sfn = FALSE;
1733               fat_cannonicalize_sfn(sfn, &created_entry[created_entry_len - FAT_DIRENT_SIZE]);
1734
1735               do
1736               {
1737                  err = fat_read_dirent(partition, file, &ent, NULL);
1738                  if (err)
1739                     goto done;
1740
1741                  if (!mame_stricmp(sfn, ent.short_filename))
1742                  {
1743                     bumped_sfn = TRUE;
1744                     fat_bump_dirent(partition, created_entry, created_entry_len);
1745                     fat_cannonicalize_sfn(sfn, &created_entry[created_entry_len - FAT_DIRENT_SIZE]);
1746                  }
1747               }
1748               while(!ent.eof);
1749            }
1750            while(bumped_sfn);
1751         }
1752
1753         LOG(("fat_lookup_path(): creating entry; pos=%u length=%u\n", freeent.position, freeent.required_size));
1754
1755         err = fat_set_file_size(partition, file, MAX(file->filesize, freeent.position + created_entry_len));
1756         if (err)
1757            goto done;
1758
1759         err = fat_seek_file(partition, file, freeent.position);
1760         if (err)
1761            goto done;
1762         
1763         err = fat_write_file(partition, file, created_entry, created_entry_len, NULL);
1764         if (err)
1765            goto done;
1766
1767         /* we have to do a special seek operation to get the main dirent */
1768         err = fat_seek_file(partition, file, freeent.position + created_entry_len - FAT_DIRENT_SIZE);
1769         if (err)
1770            goto done;
1771         entry_sector_index = fat_get_filepos_sector_index(partition, file);
1772         entry_sector_offset = file->index % FAT_SECLEN;
1773
1774         /* build the file struct for the newly created file/directory */
1775         memset(file, 0, sizeof(*file));
1776         file->directory = (created_entry[created_entry_len - FAT_DIRENT_SIZE + 11] & 0x10) ? 1 : 0;
1777         file->dirent_sector_index = entry_sector_index;
1778         file->dirent_sector_offset = entry_sector_offset;
1779      }
1780      else
1781      {
1782         /* update the current file */
1783         memset(file, 0, sizeof(*file));
1784         file->directory = ent.directory;
1785         file->filesize = ent.filesize;
1786         file->cluster = ent.first_cluster;
1787         file->first_cluster = ent.first_cluster;
1788         file->dirent_sector_index = ent.dirent_sector_index;
1789         file->dirent_sector_offset = ent.dirent_sector_offset;
1790      }
1791
1792      path = next_path_part;
1793      file->parent_first_cluster = parent_first_cluster;
1794   }
1795
1796   err = IMGTOOLERR_SUCCESS;
1797
1798done:
1799   if (created_entry)
1800      free(created_entry);
1801   return err;
1802}
1803
1804
1805
1806static imgtoolerr_t fat_partition_beginenum(imgtool_directory *enumeration, const char *path)
1807{
1808   imgtoolerr_t err;
1809   fat_file *file;
1810
1811   file = (fat_file *) imgtool_directory_extrabytes(enumeration);
1812
1813   err = fat_lookup_path(imgtool_directory_partition(enumeration), path, CREATE_NONE, file);
1814   if (err)
1815      return err;
1816   if (!file->directory)
1817      return IMGTOOLERR_PATHNOTFOUND;
1818   return IMGTOOLERR_SUCCESS;
1819}
1820
1821
1822
1823static imgtoolerr_t fat_partition_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
1824{
1825   imgtoolerr_t err;
1826   fat_file *file;
1827   fat_dirent fatent;
1828
1829   file = (fat_file *) imgtool_directory_extrabytes(enumeration);
1830   err = fat_read_dirent(imgtool_directory_partition(enumeration), file, &fatent, NULL);
1831   if (err)
1832      return err;
1833
1834   /* copy stuff from the FAT dirent to the Imgtool dirent */
1835   snprintf(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), "%s", fatent.long_filename[0]
1836      ? fatent.long_filename : fatent.short_filename);
1837   ent->filesize = fatent.filesize;
1838   ent->directory = fatent.directory;
1839   ent->eof = fatent.eof;
1840   ent->creation_time = fatent.creation_time;
1841   ent->lastmodified_time = fatent.lastmodified_time;
1842   return IMGTOOLERR_SUCCESS;
1843}
1844
1845
1846
1847static imgtoolerr_t fat_read_bootblock(imgtool_partition *partition, imgtool_stream *stream)
1848{
1849   imgtoolerr_t err;
1850   UINT8 block[FAT_SECLEN];
1851
1852   err = fat_read_sector(partition, 0, 0, block, sizeof(block));
1853   if (err)
1854      return err;
1855
1856   stream_write(stream, block, sizeof(block));
1857   return IMGTOOLERR_SUCCESS;
1858}
1859
1860
1861
1862static imgtoolerr_t fat_write_bootblock(imgtool_partition *partition, imgtool_stream *stream)
1863{
1864   imgtoolerr_t err;
1865   UINT8 block[FAT_SECLEN];
1866   UINT8 new_block[FAT_SECLEN];
1867
1868   if (stream_size(stream) != sizeof(new_block))
1869      return IMGTOOLERR_UNEXPECTED;
1870   stream_read(stream, new_block, sizeof(new_block));
1871
1872   if (new_block[510] != 0x55)
1873      return IMGTOOLERR_UNEXPECTED;
1874   if (new_block[511] != 0xAA)
1875      return IMGTOOLERR_UNEXPECTED;
1876
1877   /* read current boot sector */
1878   err = fat_read_sector(partition, 0, 0, block, sizeof(block));
1879   if (err)
1880      return err;
1881
1882   /* merge in the new stuff */
1883   memcpy(&block[ 0], &new_block[ 0],   3);
1884   memcpy(&block[62], &new_block[62], 448);
1885
1886   /* and write it out */
1887   err = fat_write_sector(partition, 0, 0, block, sizeof(block));
1888   if (err)
1889      return err;
1890
1891   return IMGTOOLERR_SUCCESS;
1892}
1893
1894
1895
1896static imgtoolerr_t fat_partition_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
1897{
1898   imgtoolerr_t err;
1899   fat_file file;
1900   size_t bytes_read;
1901   char buffer[1024];
1902
1903   /* special case for bootblock */
1904   if (filename == FILENAME_BOOTBLOCK)
1905      return fat_read_bootblock(partition, destf);
1906
1907   err = fat_lookup_path(partition, filename, CREATE_NONE, &file);
1908   if (err)
1909      return err;
1910
1911   if (file.directory)
1912      return IMGTOOLERR_FILENOTFOUND;
1913
1914   do
1915   {
1916      err = fat_read_file(partition, &file, buffer, sizeof(buffer), &bytes_read);
1917      if (err)
1918         return err;
1919
1920      stream_write(destf, buffer, bytes_read);
1921   }
1922   while(bytes_read > 0);
1923   return IMGTOOLERR_SUCCESS;
1924}
1925
1926
1927
1928static imgtoolerr_t fat_partition_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
1929{
1930   imgtoolerr_t err;
1931   fat_file file;
1932   UINT32 bytes_left, len;
1933   char buffer[1024];
1934
1935   /* special case for bootblock */
1936   if (filename == FILENAME_BOOTBLOCK)
1937      return fat_write_bootblock(partition, sourcef);
1938
1939   err = fat_lookup_path(partition, filename, CREATE_FILE, &file);
1940   if (err)
1941      return err;
1942
1943   if (file.directory)
1944      return IMGTOOLERR_FILENOTFOUND;
1945
1946   bytes_left = (UINT32) stream_size(sourcef);
1947
1948   err = fat_set_file_size(partition, &file, bytes_left);
1949   if (err)
1950      return err;
1951
1952   while(bytes_left > 0)
1953   {
1954      len = MIN(bytes_left, sizeof(buffer));
1955      stream_read(sourcef, buffer, len);
1956
1957      err = fat_write_file(partition, &file, buffer, len, NULL);
1958      if (err)
1959         return err;
1960
1961      bytes_left -= len;
1962   }
1963   return IMGTOOLERR_SUCCESS;
1964}
1965
1966
1967
1968static imgtoolerr_t fat_partition_delete(imgtool_partition *partition, const char *filename, unsigned int dir)
1969{
1970   imgtoolerr_t err;
1971   fat_file file;
1972   fat_dirent ent;
1973
1974   err = fat_lookup_path(partition, filename, CREATE_NONE, &file);
1975   if (err)
1976      return err;
1977   if (file.directory != dir)
1978      return IMGTOOLERR_FILENOTFOUND;
1979
1980   if (dir)
1981   {
1982      err = fat_read_dirent(partition, &file, &ent, NULL);
1983      if (err)
1984         return err;
1985      if (!ent.eof)
1986         return IMGTOOLERR_DIRNOTEMPTY;
1987   }
1988
1989   err = fat_set_file_size(partition, &file, ~0);
1990   if (err)
1991      return err;
1992
1993   return IMGTOOLERR_SUCCESS;
1994}
1995
1996
1997
1998static imgtoolerr_t fat_partition_deletefile(imgtool_partition *partition, const char *filename)
1999{
2000   return fat_partition_delete(partition, filename, 0);
2001}
2002
2003
2004
2005static imgtoolerr_t fat_partition_freespace(imgtool_partition *partition, UINT64 *size)
2006{
2007   imgtoolerr_t err;
2008   const fat_partition_info *disk_info;
2009   UINT8 *fat_table;
2010   UINT32 i;
2011
2012   disk_info = fat_get_partition_info(partition);
2013
2014   err = fat_load_fat(partition, &fat_table);
2015   if (err)
2016      goto done;
2017
2018   *size = 0;
2019   for (i = 2; i < disk_info->total_clusters; i++)
2020   {
2021      if (fat_get_fat_entry(partition, fat_table, i) == 0)
2022         *size += disk_info->cluster_size;
2023   }
2024
2025done:
2026   if (fat_table)
2027      free(fat_table);
2028   return err;
2029}
2030
2031
2032
2033static imgtoolerr_t fat_partition_createdir(imgtool_partition *partition, const char *path)
2034{
2035   imgtoolerr_t err;
2036   fat_file file;
2037   UINT8 initial_data[64];
2038
2039   err = fat_lookup_path(partition, path, CREATE_DIR, &file);
2040   if (err)
2041      return err;
2042   if (!file.directory)
2043      return IMGTOOLERR_FILENOTFOUND;
2044
2045   err = fat_set_file_size(partition, &file, sizeof(initial_data));
2046   if (err)
2047      return err;
2048
2049   /* set up the two directory entries in all directories */
2050   memset(initial_data, 0, sizeof(initial_data));
2051   memcpy(&initial_data[0], ".          ", 11);
2052   place_integer_le(initial_data, 11, 1, 0x10);
2053   place_integer_le(initial_data, 26, 2, file.first_cluster);
2054   memcpy(&initial_data[32], ".          ", 11);
2055   place_integer_le(initial_data, 43, 1, 0x10);
2056   place_integer_le(initial_data, 58, 2, file.parent_first_cluster);
2057
2058   err = fat_write_file(partition, &file, initial_data, sizeof(initial_data), NULL);
2059   if (err)
2060      return err;
2061
2062   return IMGTOOLERR_SUCCESS;
2063}
2064
2065
2066
2067static imgtoolerr_t fat_partition_deletedir(imgtool_partition *partition, const char *path)
2068{
2069   return fat_partition_delete(partition, path, 1);
2070}
2071
2072
2073
2074void fat_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2075{
2076   switch(state)
2077   {
2078      /* --- the following bits of info are returned as 64-bit signed integers --- */
2079      case IMGTOOLINFO_INT_INITIAL_PATH_SEPARATOR:      info->i = 1; break;
2080      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
2081      case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME:      info->i = 1; break;
2082      case IMGTOOLINFO_INT_SUPPORTS_LASTMODIFIED_TIME:   info->i = 1; break;
2083      case IMGTOOLINFO_INT_SUPPORTS_BOOTBLOCK:         info->i = 1; break;
2084      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = '\\'; break;
2085      case IMGTOOLINFO_INT_ALTERNATE_PATH_SEPARATOR:      info->i = '/'; break;
2086      case IMGTOOLINFO_INT_PARTITION_EXTRA_BYTES:         info->i = sizeof(fat_partition_info); break;
2087      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:         info->i = sizeof(fat_file); break;
2088
2089      /* --- the following bits of info are returned as NULL-terminated strings --- */
2090      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
2091      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r\n"); break;
2092
2093      /* --- the following bits of info are returned as pointers to data or functions --- */
2094      case IMGTOOLINFO_PTR_CREATE_PARTITION:            info->create_partition = fat_partition_create; break;
2095      case IMGTOOLINFO_PTR_OPEN_PARTITION:            info->open_partition = fat_partition_open; break;
2096      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = fat_partition_beginenum; break;
2097      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = fat_partition_nextenum; break;
2098      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = fat_partition_readfile; break;
2099      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = fat_partition_writefile; break;
2100      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = fat_partition_deletefile; break;
2101      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = fat_partition_freespace; break;
2102      case IMGTOOLINFO_PTR_CREATE_DIR:               info->create_dir = fat_partition_createdir; break;
2103      case IMGTOOLINFO_PTR_DELETE_DIR:               info->delete_dir = fat_partition_deletedir; break;
2104   }
2105}
src/mess/tools/imgtool/t64.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6
7#ifdef LSB_FIRST
8typedef UINT16 littleuword;
9typedef UINT32 littleulong;
10#define GET_UWORD(a) a
11#define GET_ULONG(a) a
12#define SET_UWORD(a,v) a=v
13#define SET_ULONG(a,v) a=v
14#else
15typedef struct {
16   unsigned char low, high;
17} littleuword;
18typedef struct {
19   unsigned char low, mid, high, highest;
20} littleulong;
21#define GET_UWORD(a) (a.low|(a.high<<8))
22#define GET_ULONG(a) (a.low|(a.mid<<8)|(a.high<<16)|(a.highest<<24))
23#define SET_UWORD(a,v) a.low=(v)&0xff;a.high=((v)>>8)&0xff
24#define SET_ULONG(a,v) a.low=(v)&0xff;a.mid=((v)>>8)&0xff;a.high=((v)>>16)&0xff;a.highest=((v)>>24)&0xff
25#endif
26
27/*
28T64 File Structure was developed by Miha Peternel for use in C64S.
29It is easy to use and allows future extensions.
30
31______________________
32  T64 file structure
33
34  Offset, size, description
35       0, 64    tape record
36      64, 32*n  file records for n directory entries
37 64+32*n, ???   binary contents of the files
38
39_______________
40  Tape Record
41
42  Offset, size, description
43       0, 32    DOS tape description + EOF (for type)
44      32, 2     tape version ($0101)
45      34, 2     number of directory entries
46      36, 2     number of used entries (can be 0 in my loader)
47      38, 2     free
48      40, 24    user description as displayed in tape menu
49
50_______________
51  File Record
52
53  Offset, size, description
54       0, 1     entry type
55                0 = free entry
56                1 = normal tape file
57                3 = memory snapshot v0.9, uncompressed
58                2..255 reserved (for memory snapshots...)
59       1, 1     C64 file type
60       2, 2     start address
61       4, 2     end address
62       6, 2     free
63       8, 4     offset of file contents start within T64 file
64      12, 4     free
65      16, 16    C64 file name
66
67*/
68 
69typedef struct{
70   char dostext[0x20]; // dos text
71   littleuword version; // packed bcd
72   littleuword max_entries;
73   littleuword used_entries;
74   littleuword reserved;
75   char description[24];
76} t64_header;
77   
78typedef struct {
79   unsigned char type;
80   unsigned char file_type;
81   littleuword start_address;
82   littleuword end_address;
83   littleuword reserved;
84   littleulong offset;
85   littleulong reserved2;
86   char name[0x10];
87} t64_entry;
88
89typedef struct {
90   imgtool_image base;
91   imgtool_stream *file_handle;
92   int size;
93   int modified;
94   unsigned char *data;
95} t64_image;
96
97#define HEADER(image) ((t64_header*)image->data)
98#define ENTRY(image, index) ((t64_entry*)(image->data+sizeof(t64_header))+index)
99
100typedef struct {
101   imgtool_directory base;
102   t64_image *image;
103   int index;
104} t64_iterator;
105
106static int t64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
107static void t64_image_exit(imgtool_image *img);
108static void t64_image_info(imgtool_image *img, char *string, const int len);
109static int t64_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
110static int t64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
111static void t64_image_closeenum(imgtool_directory *enumeration);
112//static size_t t64_image_freespace(imgtool_image *img);
113static int t64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
114static int t64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *_options);
115static int t64_image_deletefile(imgtool_image *img, const char *fname);
116static int t64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options);
117
118static struct OptionTemplate t64_createopts[] =
119{
120   { "entries", NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      3,      NULL   },   /* [0] */
121   { "label", NULL, IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,   0,      0,      NULL   },   /* [1] */
122   { NULL, NULL, 0, 0, 0, 0 }
123};
124
125#define T64_OPTION_ENTRIES   0
126#define T64_OPTION_LABEL   1
127
128IMAGEMODULE(
129   t64,
130   "Commodore 64 Archive for Tapes",   /* human readable name */
131   "t64",                        /* file extension */
132   NULL,                        /* crcfile */
133   NULL,                        /* crc system name */
134   EOLN_CR,                     /* eoln */
135   0,                           /* flags */
136   t64_image_init,                  /* init function */
137   t64_image_exit,                  /* exit function */
138   t64_image_info,                  /* info function */
139   t64_image_beginenum,            /* begin enumeration */
140   t64_image_nextenum,               /* enumerate next */
141   t64_image_closeenum,            /* close enumeration */
142   NULL, //t64_image_freespace,      /* free space on image */
143   t64_image_readfile,               /* read file */
144   t64_image_writefile,            /* write file */
145   t64_image_deletefile,            /* delete file */
146   t64_image_create,               /* create image */
147   NULL,                        /* read sector */
148   NULL,                        /* write sector */
149   NULL,                        /* file _options */
150   t64_createopts                  /* create options */
151)
152
153static int t64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
154{
155   t64_image *image;
156
157   image=*(t64_image**)outimg=(t64_image *) malloc(sizeof(t64_image));
158   if (!image) return IMGTOOLERR_OUTOFMEMORY;
159
160   memset(image, 0, sizeof(t64_image));
161   image->base.module = mod;
162   image->size=stream_size(f);
163   image->file_handle=f;
164
165   image->data = (unsigned char *) malloc(image->size);
166   if ( (!image->data)
167       ||(stream_read(f, image->data, image->size)!=image->size) ) {
168      free(image);
169      *outimg=NULL;
170      return IMGTOOLERR_OUTOFMEMORY;
171   }
172
173   return 0;
174}
175
176static void t64_image_exit(imgtool_image *img)
177{
178   t64_image *image=(t64_image*)img;
179   if (image->modified) {
180      stream_clear(image->file_handle);
181      stream_write(image->file_handle, image->data, image->size);
182   }
183   stream_close(image->file_handle);
184   free(image->data);
185   free(image);
186}
187
188static void t64_image_info(imgtool_image *img, char *string, const int len)
189{
190   t64_image *image=(t64_image*)img;
191   char dostext_with_null[33]= { 0 };
192   char name_with_null[25]={ 0 };
193   strncpy(dostext_with_null, HEADER(image)->dostext, 32);
194   strncpy(name_with_null, HEADER(image)->description, 24);
195   sprintf(string,"%s\n%s\nversion:%.4x max entries:%d",
196         dostext_with_null,
197         name_with_null,
198         GET_UWORD(HEADER(image)->version),
199         HEADER(image)->max_entries);
200}
201
202static int t64_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
203{
204   t64_image *image=(t64_image*)img;
205   t64_iterator *iter;
206
207   iter=*(t64_iterator**)outenum = (t64_iterator *) malloc(sizeof(t64_iterator));
208   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
209
210   iter->base.module = img->module;
211
212   iter->image=image;
213   iter->index = 0;
214   return 0;
215}
216
217static int t64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
218{
219   t64_iterator *iter=(t64_iterator*)enumeration;
220   ent->corrupt=0;
221   
222   for (;!(ent->eof=(iter->index>=GET_UWORD(HEADER(iter->image)->max_entries)));iter->index++ ){
223      if (ENTRY(iter->image, iter->index)->type==0) continue;
224      memset(ent->fname,0,17);
225      strncpy(ent->fname, ENTRY(iter->image, iter->index)->name, 16);
226      if (ent->attr)
227         sprintf(ent->attr,"start:%.4x end:%.4x type:%d file:%d",
228               GET_UWORD( ENTRY(iter->image,iter->index)->start_address),
229               GET_UWORD( ENTRY(iter->image,iter->index)->end_address),
230               ENTRY(iter->image,iter->index)->type,
231               ENTRY(iter->image,iter->index)->file_type );
232      ent->filesize=GET_UWORD( ENTRY(iter->image, iter->index)->end_address )
233         -GET_UWORD( ENTRY(iter->image, iter->index)->start_address );
234      iter->index++;
235      break;
236   }
237   return 0;
238}
239
240static void t64_image_closeenum(imgtool_directory *enumeration)
241{
242   free(enumeration);
243}
244
245#if 0
246static size_t t64_image_freespace(imgtool_image *img)
247{
248   int i;
249   rsdos_diskimage *rsimg = (rsdos_diskimage *) img;
250   size_t s = 0;
251
252   for (i = 0; i < GRANULE_COUNT; i++)
253      if (rsimg->granulemap[i] == 0xff)
254         s += (9 * 256);
255   return s;
256}
257#endif
258
259static int t64_image_findfile(t64_image *image, const char *fname)
260{
261   int i=0;
262
263   for (i=0; i<GET_UWORD(HEADER(image)->max_entries); i++) {
264      if (ENTRY(image, i)->type==0) continue;
265      if (!strnicmp(fname, ENTRY(image,i)->name, strlen(fname)) ) return i;
266   }
267   return -1;
268}
269
270static int t64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
271{
272   t64_image *image=(t64_image*)img;
273   int size;
274   int ind;
275
276   if ((ind=t64_image_findfile(image, fname))==-1 ) return IMGTOOLERR_MODULENOTFOUND;
277
278   size=GET_UWORD( ENTRY(image, ind)->end_address )-GET_UWORD( ENTRY(image, ind)->start_address );
279
280   if (stream_write(destf, &ENTRY(image, ind)->start_address, 2)!=2) {
281      return IMGTOOLERR_WRITEERROR;
282   }
283   if (stream_write(destf, image->data+GET_ULONG(ENTRY(image, ind)->offset), size)!=size) {
284      return IMGTOOLERR_WRITEERROR;
285   }
286
287   return 0;
288}
289
290static int t64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *_options)
291{
292   t64_image *image=(t64_image*)img;
293   int size, fsize;
294   int ind;
295   int pos, i, t;
296
297   fsize=stream_size(sourcef);
298   if ((ind=t64_image_findfile(image, fname))==-1 ) {
299      // appending
300      for (ind=0; ind<GET_UWORD(HEADER(image)->max_entries)&&(ENTRY(image,ind)->type!=0); ind++) ;
301      if (ind>=GET_UWORD(HEADER(image)->max_entries)) return IMGTOOLERR_NOSPACE;
302      pos=image->size;
303      if (!(image->data=realloc(image->data, image->size+fsize-2)) )
304         return IMGTOOLERR_OUTOFMEMORY;
305      image->size+=fsize-2;
306#ifdef LSB_FIRST
307      HEADER(image)->used_entries++;
308#else
309      if (++HEADER(image)->used_entries.low == 0)
310         HEADER(image)->used_entries.high++;
311#endif
312   } else {
313      pos=GET_ULONG(ENTRY(image,ind)->offset);
314      // find the size of the data in this area
315      for (size=image->size-pos, i=0; i<GET_UWORD(HEADER(image)->max_entries); i++) {
316         if (ENTRY(image,i)->type==0) continue;
317         if (GET_UWORD(ENTRY(image,i)->offset)<pos) continue;
318         if (GET_ULONG(ENTRY(image,i)->offset)-pos>=size) continue;
319         size=GET_ULONG(ENTRY(image, i)->offset)-pos;
320      }
321      if ((size!=0)&&(image->size-pos-size!=0))
322         memmove(image->data+pos, image->data+pos+size, image->size-pos-size);
323      // correct offset positions in other entries
324      for (i=0;i<GET_UWORD(HEADER(image)->max_entries); i++) {
325         if (i==ind) continue;
326         if (ENTRY(image,i)->type==0) continue;
327         if (GET_ULONG(ENTRY(image,i)->offset)<pos) continue;
328         t=GET_ULONG(ENTRY(image,i)->offset)-size;
329         SET_ULONG( ENTRY(image,i)->offset, t);
330      }
331      // overwritting
332      if (!(image->data=realloc(image->data, image->size+fsize-2-size)))
333         return IMGTOOLERR_OUTOFMEMORY;
334      pos=image->size;
335      image->size=image->size+fsize-2-size;
336   }
337   memset(ENTRY(image,ind), 0, sizeof(t64_entry));
338   if (stream_read(sourcef, &ENTRY(image,ind)->start_address, 2)!=2) {
339      return IMGTOOLERR_READERROR;
340   }
341   if (stream_read(sourcef, image->data+pos, fsize-2)!=fsize-2) {
342      return IMGTOOLERR_READERROR;
343   }
344   SET_UWORD( ENTRY(image, ind)->end_address,
345            GET_UWORD( ENTRY(image, ind)->start_address)+fsize-2);
346   SET_ULONG( ENTRY(image, ind)->offset, pos);
347   strncpy(ENTRY(image, ind)->name, fname, 16);
348   ENTRY(image,ind)->type=1; // normal file
349   ENTRY(image,ind)->file_type=1; // prg
350   image->modified=1;
351
352   return 0;
353}
354
355static int t64_image_deletefile(imgtool_image *img, const char *fname)
356{
357   t64_image *image=(t64_image*)img;
358   int pos, size;
359   int ind, i;
360
361   if ((ind=t64_image_findfile(image, fname))==-1 ) {
362      return IMGTOOLERR_MODULENOTFOUND;
363   }
364   pos=GET_ULONG(ENTRY(image,ind)->offset);
365   // find the size of the data in this area
366   for (size=image->size-pos, i=0; i<GET_UWORD(HEADER(image)->max_entries); i++) {
367      if (ENTRY(image,i)->type==0) continue;
368      if (GET_UWORD(ENTRY(image,i)->offset)<pos) continue;
369      if (GET_ULONG(ENTRY(image,i)->offset)-pos>=size) continue;
370      size=GET_ULONG(ENTRY(image, i)->offset)-pos;
371   }
372   if ((size!=0)&&(image->size-pos-size!=0))
373      memmove(image->data+pos, image->data+pos+size, image->size-pos-size);
374   // correct offset positions in other entries
375   for (i=0;i<GET_UWORD(HEADER(image)->max_entries); i++) {
376      if (i==ind) continue;
377      if (ENTRY(image,i)->type==0) continue;
378      if (GET_ULONG(ENTRY(image,i)->offset)<pos) continue;
379      SET_ULONG( ENTRY(image,i)->offset, GET_ULONG(ENTRY(image,i)->offset)-size );
380   }
381   image->size-=size;
382   ENTRY(image,ind)->type=0; // normal file
383   image->modified=1;
384#ifdef LSB_FIRST
385   HEADER(image)->used_entries--;
386#else
387      if (HEADER(image)->used_entries.low-- == 0)
388         HEADER(image)->used_entries.high--;
389#endif
390
391   return 0;
392}
393
394static int t64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options)
395{
396   int entries;
397   t64_header header={ "T64 Tape archiv created by MESS\x1a" };
398   t64_entry entry= { 0 };
399   int i;
400
401   entries = _options[T64_OPTION_ENTRIES].i;
402   if (entries==0) entries=10;
403   SET_UWORD(header.version, 0x0101);
404   SET_UWORD(header.max_entries, entries);
405   if (_options[T64_OPTION_LABEL].s) strcpy(header.description, _options[T64_OPTION_LABEL].s);
406   if (stream_write(f, &header, sizeof(t64_header)) != sizeof(t64_header))
407      return  IMGTOOLERR_WRITEERROR;
408   for (i=0; i<entries; i++) {
409   if (stream_write(f, &entry, sizeof(t64_entry)) != sizeof(t64_entry))
410      return  IMGTOOLERR_WRITEERROR;
411   }
412
413   return 0;
414}
415
src/mess/tools/imgtool/pc_flop.c
r1339r1340
1/****************************************************************************
2
3   pc_flop.c
4
5   PC floppies
6
7****************************************************************************/
8
9#include "imgtool.h"
10#include "formats/pc_dsk.h"
11#include "iflopimg.h"
12
13#define FAT_SECLEN            512
14
15/* imports from fat.c */
16extern void fat_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info);
17
18
19
20static imgtoolerr_t fat_image_create(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
21{
22   imgtoolerr_t err;
23   UINT32 tracks, heads, sectors;
24   UINT8 buffer[FAT_SECLEN];
25   imgtool_class imgclass = { fat_get_info };
26   imgtoolerr_t (*fat_partition_create)(imgtool_image *image, UINT64 first_block, UINT64 block_count);
27
28   tracks = option_resolution_lookup_int(opts, 'T');
29   heads = option_resolution_lookup_int(opts, 'H');
30   sectors = option_resolution_lookup_int(opts, 'S');
31
32   /* set up just enough of a boot sector to specify geometry */
33   memset(buffer, 0, sizeof(buffer));
34   place_integer_le(buffer, 24, 2, sectors);
35   place_integer_le(buffer, 26, 2, heads);
36   place_integer_le(buffer, 19, 2, (UINT16) (((UINT64) tracks * heads * sectors) >> 0));
37   place_integer_le(buffer, 32, 4, (UINT16) (((UINT64) tracks * heads * sectors) >> 16));
38   err = imgtool_image_write_block(image, 0, buffer);
39   if (err)
40      goto done;
41
42   /* load fat_partition_create */
43   fat_partition_create = (imgtoolerr_t (*)(imgtool_image *, UINT64, UINT64))
44      imgtool_get_info_fct(&imgclass, IMGTOOLINFO_PTR_CREATE_PARTITION);
45
46   /* actually create the partition */
47   err = fat_partition_create(image, 0, ((UINT64) tracks) * heads * sectors);
48   if (err)
49      goto done;
50
51done:
52   return err;
53}
54
55
56
57static imgtoolerr_t   fat_image_get_geometry(imgtool_image *image, UINT32 *tracks, UINT32 *heads, UINT32 *sectors)
58{
59   imgtoolerr_t err;
60   UINT64 total_sectors;
61   UINT8 buffer[FAT_SECLEN];
62
63   err = imgtool_image_read_block(image, 0, buffer);
64   if (err)
65      return err;
66
67   total_sectors = pick_integer_le(buffer, 19, 2)
68      | (pick_integer_le(buffer, 32, 4) << 16);
69
70   *sectors = pick_integer_le(buffer, 24, 2);
71   *heads = pick_integer_le(buffer, 26, 2);
72   *tracks = total_sectors / *heads / *sectors;
73   return IMGTOOLERR_SUCCESS;
74}
75
76
77
78static imgtoolerr_t fat_get_sector_position(imgtool_image *image, UINT32 sector_index,
79   UINT32 *track, UINT32 *head, UINT32 *sector)
80{
81   imgtoolerr_t err;
82   UINT32 tracks, heads, sectors;
83
84   if (sector_index == 0)
85   {
86      /* special case */
87      *head = 0;
88      *track = 0;
89      *sector = 1;
90   }
91   else
92   {
93      err = imgtool_image_get_geometry(image, &tracks, &heads, &sectors);
94      if (err)
95         return err;
96
97      *track = sector_index / sectors / heads;
98      *head = (sector_index / sectors) % heads;
99      *sector = 1 + (sector_index % sectors);
100   }
101   return IMGTOOLERR_SUCCESS;
102}
103
104
105
106static imgtoolerr_t fat_image_readblock(imgtool_image *image, void *buffer, UINT64 block)
107{
108   imgtoolerr_t err;
109   floperr_t ferr;
110   UINT32 track, head, sector;
111   UINT32 block_size;
112
113   err = imgtool_image_get_block_size(image, &block_size);
114   if (err)
115      return err;
116
117   err = fat_get_sector_position(image, block, &track, &head, &sector);
118   if (err)
119      return err;
120
121   ferr = floppy_read_sector(imgtool_floppy(image), head, track, sector, 0, buffer, block_size);
122   if (ferr)
123      return imgtool_floppy_error(ferr);
124   return IMGTOOLERR_SUCCESS;
125}
126
127
128
129static imgtoolerr_t fat_image_writeblock(imgtool_image *image, const void *buffer, UINT64 block)
130{
131   imgtoolerr_t err;
132   floperr_t ferr;
133   UINT32 track, head, sector;
134   UINT32 block_size;
135
136   err = imgtool_image_get_block_size(image, &block_size);
137   if (err)
138      return err;
139
140   err = fat_get_sector_position(image, block, &track, &head, &sector);
141   if (err)
142      return err;
143
144   ferr = floppy_write_sector(imgtool_floppy(image), head, track, sector, 0, buffer, block_size);
145   if (ferr)
146      return imgtool_floppy_error(ferr);
147   return IMGTOOLERR_SUCCESS;
148}
149
150
151
152void pc_floppy_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
153{
154   switch(state)
155   {
156      /* --- the following bits of info are returned as 64-bit signed integers --- */
157      case IMGTOOLINFO_INT_BLOCK_SIZE:               info->i = FAT_SECLEN; break;
158
159      /* --- the following bits of info are returned as NULL-terminated strings --- */
160      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "fat"); break;
161      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "FAT format"); break;
162
163      /* --- the following bits of info are returned as pointers to data or functions --- */
164      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
165      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = fat_image_create; break;
166      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_pc; break;
167      case IMGTOOLINFO_PTR_READ_BLOCK:               info->read_block = fat_image_readblock; break;
168      case IMGTOOLINFO_PTR_WRITE_BLOCK:               info->write_block = fat_image_writeblock; break;
169      case IMGTOOLINFO_PTR_GET_GEOMETRY:               info->get_geometry = fat_image_get_geometry; break;
170
171      default: fat_get_info(imgclass, state, info); break;
172   }
173}
src/mess/tools/imgtool/svi_cas.c
r1339r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "formats/svi_cas.h"
6#include "imgtoolx.h"
7#include "utils.h"
8
9/*
10   SVI module
11
12   SVI style .cas for the svi-318 and svi-328. Converts them to .wav files.
13   Uses the mess/formats/svi_cas.[ch] files, for the actual conversion.
14*/
15
16typedef struct {
17   imgtool_image         base;
18   char         *file_name;
19   imgtool_stream          *file_handle;
20   int          size;
21   unsigned char   *data;
22   INT16         *wavdata;
23   int          count;
24   } CAS_IMAGE;
25
26typedef struct
27   {
28   imgtool_directory    base;
29   CAS_IMAGE   *image;
30   int         index;
31   } CAS_ITERATOR;
32
33static int svi_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
34static void svi_cas_image_exit(imgtool_image *img);
35//static void svi_cas_image_info(imgtool_image *img, char *string, const int len);
36static int svi_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
37static int svi_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
38static void svi_cas_image_closeenum(imgtool_directory *enumeration);
39static int svi_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
40
41IMAGEMODULE(
42   svi_cas,
43   "SVI-318/SVI-328 .cas file",            /* human readable name */
44   "cas",                        /* file extension */
45   NULL,                        /* crcfile */
46   NULL,                        /* crc system name */
47   NULL,                        /* eoln */
48   0,
49   svi_cas_image_init,            /* init function */
50   svi_cas_image_exit,            /* exit function */
51   NULL,                        /* info function */
52   svi_cas_image_beginenum,         /* begin enumeration */
53   svi_cas_image_nextenum,         /* enumerate next */
54   svi_cas_image_closeenum,         /* close enumeration */
55   NULL,                        /* free space on image */
56   svi_cas_image_readfile,         /* read file */
57   NULL,/* write file */
58   NULL,/* delete file */
59   NULL,/* create image */
60   NULL,                        /* read sector */
61   NULL,                        /* write sector */
62   NULL,               /* file options */
63   NULL               /* create options */
64)
65
66static int svi_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
67   {
68   CAS_IMAGE *image;
69   int len, i;
70   char *pbase;
71   char default_name[] = "svitape";
72
73   image = (CAS_IMAGE*)malloc (sizeof (CAS_IMAGE) );
74   if (!image) return IMGTOOLERR_OUTOFMEMORY;
75
76   *outimg = (imgtool_image*)image;
77
78   memset(image, 0, sizeof(CAS_IMAGE));
79   image->base.module = mod;
80   image->size=stream_size(f);
81   image->file_handle=f;
82
83    if (image->size < 17)
84      {
85      free (image);
86      return IMGTOOLERR_CORRUPTIMAGE;
87      }
88
89   image->data = (unsigned char *) malloc(image->size);
90   if ( (!image->data)
91       ||(stream_read(f, image->data, image->size)!=image->size) )
92      {
93      free(image);
94      *outimg=NULL;
95      return IMGTOOLERR_OUTOFMEMORY;
96      }
97
98     i = svi_cas_to_wav (image->data, image->size, &image->wavdata, &image->count);
99     if (i)
100      {
101      free(image->data);
102      free(image);
103      *outimg=NULL;
104      return (i == 2) ? IMGTOOLERR_OUTOFMEMORY : IMGTOOLERR_CORRUPTIMAGE;
105      }
106
107    pbase = NULL;
108    if (pbase) len = strlen (pbase);
109    else len = strlen (default_name);
110
111    image->file_name = malloc (len + 5);
112   if (!image->file_name)
113      {
114      free(image->data);
115      free(image);
116      *outimg=NULL;
117      return IMGTOOLERR_CORRUPTIMAGE;
118      }
119
120    if (!pbase)
121      strcpy (image->file_name, default_name);
122    else
123      {
124      strcpy (image->file_name, pbase);
125        if (len > 4)
126         if (!strncmpi (".cas", image->file_name + len - 4, 4) ) len -= 4;
127
128      strcpy (image->file_name + len, ".wav");
129      }
130
131   return 0;
132   }
133
134static void svi_cas_image_exit(imgtool_image *img)
135   {
136   CAS_IMAGE *image=(CAS_IMAGE*)img;
137   stream_close(image->file_handle);
138   free(image->file_name);
139   free(image->data);
140   free(image->wavdata);
141   free(image);
142   }
143
144static int svi_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
145   {
146   CAS_IMAGE *image=(CAS_IMAGE*)img;
147   CAS_ITERATOR *iter;
148
149   iter=*(CAS_ITERATOR**)outenum = (CAS_ITERATOR*) malloc(sizeof(CAS_ITERATOR));
150   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
151
152   iter->base.module = img->module;
153
154   iter->image=image;
155   iter->index = 0;
156   return 0;
157   }
158
159static int svi_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
160   {
161   CAS_ITERATOR *iter=(CAS_ITERATOR*)enumeration;
162
163   ent->eof=iter->index;
164   if (!ent->eof)
165      {
166      strcpy (ent->fname, iter->image->file_name);
167      ent->corrupt=0;
168      ent->filesize = iter->image->count * 2 + 0x2c;
169      iter->index++;
170      }
171
172   return 0;
173   }
174
175static void svi_cas_image_closeenum(imgtool_directory *enumeration)
176   {
177   free(enumeration);
178   }
179
180static int svi_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
181   {
182   CAS_IMAGE *image=(CAS_IMAGE*)img;
183   INT16 *wavdata;
184   UINT16   temp16;
185   UINT32   temp32;
186   int wavlen, offset;
187
188   if (mame_stricmp (fname, image->file_name) )
189      return IMGTOOLERR_MODULENOTFOUND;
190
191   wavdata = image->wavdata;
192   wavlen = image->count;
193    /* write the core header for a WAVE file */
194   offset = stream_write(destf, "RIFF", 4);
195    if( offset < 4 )
196      return IMGTOOLERR_WRITEERROR;
197
198   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2 + 0x24);
199   offset += stream_write(destf, &temp32, 4);
200    if( offset < 8 )
201      return IMGTOOLERR_WRITEERROR;
202
203   /* read the RIFF file type and make sure it's a WAVE file */
204   offset += stream_write(destf, "WAVEfmt ", 8);
205   if( offset < 16 )
206      return IMGTOOLERR_WRITEERROR;
207
208    /* size of the following 'fmt ' fields */
209    offset += stream_write(destf, "\x10\x00\x00\x00", 4);
210   if( offset < 20 )
211      return IMGTOOLERR_WRITEERROR;
212
213   /* format: PCM */
214   temp16 = LITTLE_ENDIANIZE_INT16 (1);
215   offset += stream_write(destf, &temp16, 2);
216   if( offset < 22 )
217      return IMGTOOLERR_WRITEERROR;
218
219   /* channels: 1 (mono) */
220   temp16 = LITTLE_ENDIANIZE_INT16 (1);
221   offset += stream_write(destf, &temp16, 2);
222   if( offset < 24 )
223      return IMGTOOLERR_WRITEERROR;
224
225   /* sample rate */
226   temp32 = LITTLE_ENDIANIZE_INT32(22050);
227   offset += stream_write(destf, &temp32, 4);
228   if( offset < 24 )
229      return IMGTOOLERR_WRITEERROR;
230
231   /* byte rate */
232   temp32 = LITTLE_ENDIANIZE_INT32(22050 * 2);
233   offset += stream_write(destf, &temp32, 4);
234   if( offset < 28 )
235      return IMGTOOLERR_WRITEERROR;
236
237   /* block align (size of one `sample') */
238   temp16 = LITTLE_ENDIANIZE_INT16 (2);
239   offset += stream_write(destf, &temp16, 2);
240   if( offset < 30 )
241      return IMGTOOLERR_WRITEERROR;
242
243   /* block align */
244   temp16 = LITTLE_ENDIANIZE_INT16 (16);
245   offset += stream_write(destf, &temp16, 2);
246   if( offset < 32 )
247      return IMGTOOLERR_WRITEERROR;
248
249   /* 'data' tag */
250   offset += stream_write(destf, "data", 4);
251   if( offset < 36 )
252      return IMGTOOLERR_WRITEERROR;
253
254   /* data size */
255   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2);
256   offset += stream_write(destf, &temp32, 4);
257   if( offset < 40 )
258      return IMGTOOLERR_WRITEERROR;
259
260   if (stream_write(destf, wavdata, (image->count*2))!=(image->count*2))
261      return IMGTOOLERR_WRITEERROR;
262
263   return 0;
264   }
265
src/mess/tools/imgtool/rsdos.c
r1339r1340
1/****************************************************************************
2
3   rsdos.c
4
5   CoCo RS-DOS disk images
6
7****************************************************************************/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include "osdepend.h"
13#include "imgtoolx.h"
14#include "utils.h"
15#include "formats/coco_dsk.h"
16#include "iflopimg.h"
17#include "utils.h"
18
19
20/* this structure mirrors the structure of an RS-DOS directory entry on disk */
21struct rsdos_dirent
22{
23   char fname[8];
24   char fext[3];
25   char ftype;
26   char asciiflag;
27   unsigned char first_granule;
28   unsigned char lastsectorbytes_msb;
29   unsigned char lastsectorbytes_lsb;
30   unsigned char unused[16];
31};
32
33struct rsdos_direnum
34{
35   int index;
36   int eof;
37};
38
39#define RSDOS_OPTIONS_FTYPE      'T'
40#define RSDOS_OPTIONS_ASCII      'M'
41
42
43
44/*********************************************************************
45   Imgtool module code
46*********************************************************************/
47
48#define MAX_DIRENTS      ((18-2)*(256/32))
49static floperr_t get_rsdos_dirent(imgtool_image *f, int index_loc, struct rsdos_dirent *ent)
50{
51   return floppy_read_sector(imgtool_floppy(f), 0, 17, 3, index_loc * 32, (void *) ent, sizeof(*ent));
52}
53
54
55
56static floperr_t put_rsdos_dirent(imgtool_image *f, int index_loc, const struct rsdos_dirent *ent)
57{
58   if (index_loc >= MAX_DIRENTS)
59      return IMGTOOLERR_FILENOTFOUND;
60   return floppy_write_sector(imgtool_floppy(f), 0, 17, 3, index_loc * 32, (void *) ent, sizeof(*ent));
61}
62
63
64
65/* fnamebuf must have at least 13 bytes */
66static void get_dirent_fname(char *fnamebuf, const struct rsdos_dirent *ent)
67{
68   char *s;
69
70   memset(fnamebuf, 0, 13);
71   memcpy(fnamebuf, ent->fname, sizeof(ent->fname));
72   rtrim(fnamebuf);
73   s = fnamebuf + strlen(fnamebuf);
74   *(s++) = '.';
75   memcpy(s, ent->fext, sizeof(ent->fext));
76   rtrim(s);
77
78   /* If no extension, remove period */
79   if (*s == '\0')
80      s[-1] = '\0';
81}
82
83
84
85static imgtoolerr_t lookup_rsdos_file(imgtool_image *f, const char *fname, struct rsdos_dirent *ent, int *position)
86{
87   int i;
88   floperr_t ferr;
89   char fnamebuf[13];
90
91   i = 0;
92   fnamebuf[0] = '\0';
93
94   do
95   {
96      do
97      {
98         ferr = get_rsdos_dirent(f, i++, ent);
99         if (ferr)
100            return imgtool_floppy_error(ferr);
101      }
102      while(ent->fname[0] == '\0');
103
104
105      if (ent->fname[0] != -1)
106         get_dirent_fname(fnamebuf, ent);
107   }
108   while((ent->fname[0] != -1) && mame_stricmp(fnamebuf, fname));
109
110   if (ent->fname[0] == -1)
111      return IMGTOOLERR_FILENOTFOUND;
112
113   if (position)
114      *position = i - 1;
115   return 0;
116}
117
118
119
120static UINT8 get_granule_count(imgtool_image *img)
121{
122   UINT16 tracks;
123   UINT16 granules;
124
125   tracks = floppy_get_tracks_per_disk(imgtool_floppy(img));
126   granules = (tracks - 1) * 2;
127   return (granules > 255) ? 255 : (UINT8) granules;
128}
129
130#define MAX_GRANULEMAP_SIZE   256
131
132/* granule_map must be an array of MAX_GRANULEMAP_SIZE bytes */
133static floperr_t get_granule_map(imgtool_image *img, UINT8 *granule_map, UINT8 *granule_count)
134{
135   UINT8 count;
136
137   count = get_granule_count(img);
138   if (granule_count)
139      *granule_count = count;
140
141   return floppy_read_sector(imgtool_floppy(img), 0, 17, 2, 0, granule_map, count);
142}
143
144
145
146static floperr_t put_granule_map(imgtool_image *img, const UINT8 *granule_map, UINT8 granule_count)
147{
148   return floppy_write_sector(imgtool_floppy(img), 0, 17, 2, 0, granule_map, granule_count);
149}
150
151
152
153
154static imgtoolerr_t transfer_granule(imgtool_image *img, UINT8 granule, int length, imgtool_stream *f, imgtoolerr_t (*proc)(imgtool_image *, int, int, int, int, size_t, imgtool_stream *))
155{
156   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
157   UINT8 track, sector;
158
159   track = granule / 2;
160   if (track >= 17)
161      track++;
162
163   sector = (granule % 2) ? 10 : 1;
164
165   if (length > 0)
166      err = proc(img, 0, track, sector, 0, length, f);
167   return err;
168}
169
170
171
172static imgtoolerr_t transfer_from_granule(imgtool_image *img, UINT8 granule, int length, imgtool_stream *destf)
173{
174   return transfer_granule(img, granule, length, destf, imgtool_floppy_read_sector_to_stream);
175}
176
177
178
179static imgtoolerr_t transfer_to_granule(imgtool_image *img, UINT8 granule, int length, imgtool_stream *sourcef)
180{
181   return transfer_granule(img, granule, length, sourcef, imgtool_floppy_write_sector_from_stream);
182}
183
184
185
186static imgtoolerr_t process_rsdos_file(struct rsdos_dirent *ent, imgtool_image *img, imgtool_stream *destf, size_t *size)
187{
188   floperr_t ferr;
189   size_t s, lastgransize;
190   UINT8 granule_count;
191   unsigned char i = 0, granule;
192   UINT8 usedmap[MAX_GRANULEMAP_SIZE];   /* Used to detect infinite loops */
193   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
194
195   ferr = get_granule_map(img, granule_map, &granule_count);
196   if (ferr)
197      return imgtool_floppy_error(ferr);
198
199   memset(usedmap, 0, granule_count);
200
201   lastgransize = ent->lastsectorbytes_lsb + (((int) ent->lastsectorbytes_msb) << 8);
202   s = 0;
203   granule = ent->first_granule;
204
205   while(!usedmap[granule] && ((i = granule_map[granule]) < granule_count))
206   {
207      usedmap[granule] = 1;
208      if (destf)
209         transfer_from_granule(img, granule, 9*256, destf);
210
211      /* i is the next granule */
212      s += (256 * 9);
213      granule = i;
214   }
215
216   if ((i < 0xc0) || (i > 0xc9))
217      return IMGTOOLERR_CORRUPTIMAGE;
218
219   if (lastgransize)
220      i--;
221   lastgransize += (256 * (i - 0xc0));
222
223   if (destf)
224      transfer_from_granule(img, granule, lastgransize, destf);
225
226   if (size)
227      *size = s + lastgransize;
228   return IMGTOOLERR_SUCCESS;
229}
230
231
232
233/* create a new directory entry with a specified name */
234static imgtoolerr_t prepare_dirent(struct rsdos_dirent *ent, const char *fname)
235{
236   const char *fname_end;
237   const char *fname_ext;
238   int fname_ext_len;
239
240   memset(ent, '\0', sizeof(*ent));
241   memset(ent->fname, ' ', sizeof(ent->fname));
242   memset(ent->fext, ' ', sizeof(ent->fext));
243
244   fname_end = strchr(fname, '.');
245   if (fname_end)
246      fname_ext = fname_end + 1;
247   else
248      fname_end = fname_ext = fname + strlen(fname);
249
250   fname_ext_len = strlen(fname_ext);
251
252   /* We had better be an 8.3 filename */
253   if (((fname_end - fname) > 8) || (fname_ext_len > 3))
254      return IMGTOOLERR_BADFILENAME;
255
256   memcpy(ent->fname, fname, fname_end - fname);
257   memcpy(ent->fext, fname_ext, fname_ext_len);
258
259   /* For now, all files are type 2 binary files */
260   ent->ftype = 2;
261   ent->asciiflag = 0;
262   return IMGTOOLERR_SUCCESS;
263}
264
265
266
267static imgtoolerr_t rsdos_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
268{
269   floperr_t ferr;
270   imgtoolerr_t err;
271   size_t filesize;
272   struct rsdos_direnum *rsenum;
273   struct rsdos_dirent rsent;
274   char fname[13];
275   imgtool_image *image;
276
277   image = imgtool_directory_image(enumeration);
278   rsenum = (struct rsdos_direnum *) imgtool_directory_extrabytes(enumeration);
279
280   /* Did we hit the end of file before? */
281   if (rsenum->eof)
282      goto eof;
283
284   do
285   {
286      if (rsenum->index >= MAX_DIRENTS)
287         goto eof;
288
289      ferr = get_rsdos_dirent(image, rsenum->index++, &rsent);
290      if (ferr)
291         return imgtool_floppy_error(ferr);
292   }
293   while(rsent.fname[0] == '\0');
294
295   /* Now are we at the eof point? */
296   if (rsent.fname[0] == -1)
297   {
298      rsenum->eof = 1;
299eof:
300      ent->eof = 1;
301   }
302   else
303   {
304      /* Not the end of file */
305      err = process_rsdos_file(&rsent, image, NULL, &filesize);
306      if (err)
307         return err;
308
309      if (filesize == ((size_t) -1))
310      {
311         /* corrupt! */
312         ent->filesize = 0;
313         ent->corrupt = 1;
314      }
315      else
316      {
317         ent->filesize = filesize;
318         ent->corrupt = 0;
319      }
320      ent->eof = 0;
321
322      get_dirent_fname(fname, &rsent);
323
324      snprintf(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), "%s", fname);
325      snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%d %c", (int) rsent.ftype, (char) (rsent.asciiflag + 'B'));
326   }
327   return IMGTOOLERR_SUCCESS;
328}
329
330
331
332static imgtoolerr_t rsdos_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
333{
334   floperr_t ferr;
335   UINT8 i;
336   size_t s = 0;
337   UINT8 granule_count;
338   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
339   imgtool_image *image = imgtool_partition_image(partition);
340
341   ferr = get_granule_map(image, granule_map, &granule_count);
342   if (ferr)
343      return imgtool_floppy_error(ferr);
344
345   for (i = 0; i < granule_count; i++)
346   {
347      if (granule_map[i] == 0xff)
348         s += (9 * 256);
349   }
350   *size = s;
351   return FLOPPY_ERROR_SUCCESS;
352}
353
354
355
356static imgtoolerr_t delete_entry(imgtool_image *img, struct rsdos_dirent *ent, int pos)
357{
358   floperr_t ferr;
359   unsigned char g, i;
360   UINT8 granule_count;
361   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
362
363   /* Write a NUL in the filename, marking it deleted */
364   ent->fname[0] = 0;
365   ferr = put_rsdos_dirent(img, pos, ent);
366   if (ferr)
367      return imgtool_floppy_error(ferr);
368
369   ferr = get_granule_map(img, granule_map, &granule_count);
370   if (ferr)
371      return imgtool_floppy_error(ferr);
372
373   /* Now free up the granules */
374   g = ent->first_granule;
375   while (g < granule_count)
376   {
377      i = granule_map[g];
378      granule_map[g] = 0xff;
379      g = i;
380   }
381
382   ferr = put_granule_map(img, granule_map, granule_count);
383   if (ferr)
384      return imgtool_floppy_error(ferr);
385
386   return IMGTOOLERR_SUCCESS;
387}
388
389
390
391static imgtoolerr_t rsdos_diskimage_readfile(imgtool_partition *partition, const char *fname, const char *fork, imgtool_stream *destf)
392{
393   imgtoolerr_t err;
394   struct rsdos_dirent ent;
395   size_t size;
396   imgtool_image *img = imgtool_partition_image(partition);
397
398   err = lookup_rsdos_file(img, fname, &ent, NULL);
399   if (err)
400      return err;
401
402   err = process_rsdos_file(&ent, img, destf, &size);
403   if (err)
404      return err;
405
406   if (size == (size_t) -1)
407      return IMGTOOLERR_CORRUPTIMAGE;
408
409   return 0;
410}
411
412
413
414static imgtoolerr_t rsdos_diskimage_writefile(imgtool_partition *partition, const char *fname, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
415{
416   floperr_t ferr;
417   imgtoolerr_t err;
418   imgtool_image *img = imgtool_partition_image(partition);
419   struct rsdos_dirent ent, ent2;
420   size_t i;
421   UINT64 sz;
422   UINT64 freespace = 0;
423   unsigned char g;
424   unsigned char *gptr;
425   UINT8 granule_count;
426   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
427
428   /* can we write to this image? */
429   if (floppy_is_read_only(imgtool_floppy(img)))
430      return IMGTOOLERR_READONLY;
431
432   err = rsdos_diskimage_freespace(partition, &freespace);
433   if (err)
434      return err;
435
436   /* is there enough space? */
437   sz = stream_size(sourcef);
438   if (sz > freespace)
439      return IMGTOOLERR_NOSPACE;
440
441   /* setup our directory entry */
442   err = prepare_dirent(&ent, fname);
443   if (err)
444      return err;
445
446   ent.ftype = option_resolution_lookup_int(writeoptions, RSDOS_OPTIONS_FTYPE);
447   ent.asciiflag = ((UINT8) option_resolution_lookup_int(writeoptions, RSDOS_OPTIONS_ASCII)) - 1;
448   ent.lastsectorbytes_lsb = sz % 256;
449   ent.lastsectorbytes_msb = (((sz % 256) == 0) && (sz > 0)) ? 1 : 0;
450   gptr = &ent.first_granule;
451
452   ferr = get_granule_map(img, granule_map, &granule_count);
453   if (ferr)
454      return imgtool_floppy_error(ferr);
455
456   g = 0x00;
457
458   do
459   {
460      while (granule_map[g] != 0xff)
461      {
462         g++;
463         if ((g >= granule_count) || (g == 0))
464            return IMGTOOLERR_UNEXPECTED;   /* We should have already verified that there is enough space */
465      }
466      *gptr = g;
467      gptr = &granule_map[g];
468
469
470      i = MIN(sz, (9*256));
471      err = transfer_to_granule(img, g, i, sourcef);
472      if (err)
473         return err;
474
475      sz -= i;
476
477      /* Go to next granule */
478      g++;
479   }
480   while(sz > 0);
481
482   /* Now that we are done with the file, we need to specify the final entry
483    * in the file allocation table
484    */
485   *gptr = 0xc0 + ((i + 255) / 256);
486
487   /* Now we need to find an empty directory entry */
488   i = -1;
489   do
490   {
491      ferr = get_rsdos_dirent(img, ++i, &ent2);
492      if (ferr)
493         return imgtool_floppy_error(ferr);
494   }
495   while((ent2.fname[0] != '\0') && strcmp(ent.fname, ent2.fname) && (ent2.fname[0] != -1));
496
497   /* delete file if it already exists */
498   if (ent2.fname[0] && (ent2.fname[0] != -1))
499   {
500      err = delete_entry(img, &ent2, i);
501      if (err)
502         return err;
503   }
504
505   ferr = put_rsdos_dirent(img, i, &ent);
506   if (ferr)
507      return imgtool_floppy_error(ferr);
508
509   /* write the granule map back out */
510   ferr = put_granule_map(img, granule_map, granule_count);
511   if (ferr)
512      return imgtool_floppy_error(ferr);
513
514   return IMGTOOLERR_SUCCESS;
515}
516
517
518
519static imgtoolerr_t rsdos_diskimage_deletefile(imgtool_partition *partition, const char *fname)
520{
521   imgtoolerr_t err;
522   imgtool_image *image = imgtool_partition_image(partition);
523   int pos;
524   struct rsdos_dirent ent;
525
526   err = lookup_rsdos_file(image, fname, &ent, &pos);
527   if (err)
528      return err;
529
530   return delete_entry(image, &ent, pos);
531}
532
533
534
535static imgtoolerr_t rsdos_diskimage_suggesttransfer(imgtool_partition *partition, const char *fname, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
536{
537   imgtoolerr_t err;
538   imgtool_image *image = imgtool_partition_image(partition);
539   struct rsdos_dirent ent;
540   int pos;
541
542   if (fname)
543   {
544      err = lookup_rsdos_file(image, fname, &ent, &pos);
545      if (err)
546         return err;
547
548      if (ent.asciiflag == (char) 0xFF)
549      {
550         /* ASCII file */
551         suggestions[0].viability = SUGGESTION_RECOMMENDED;
552         suggestions[0].filter = filter_eoln_getinfo;
553         suggestions[1].viability = SUGGESTION_POSSIBLE;
554         suggestions[1].filter = NULL;
555      }
556      else if (ent.ftype == 0)
557      {
558         /* tokenized BASIC file */
559         suggestions[0].viability = SUGGESTION_RECOMMENDED;
560         suggestions[0].filter = NULL;
561         suggestions[1].viability = SUGGESTION_POSSIBLE;
562         suggestions[1].filter = filter_cocobas_getinfo;
563      }
564   }
565   else
566   {
567      suggestions[0].viability = SUGGESTION_RECOMMENDED;
568      suggestions[0].filter = NULL;
569      suggestions[1].viability = SUGGESTION_POSSIBLE;
570      suggestions[1].filter = filter_eoln_getinfo;
571   }
572
573   return IMGTOOLERR_SUCCESS;
574}
575
576
577
578/*********************************************************************
579   Imgtool module declaration
580*********************************************************************/
581
582OPTION_GUIDE_START( coco_rsdos_writefile_optionguide )
583   OPTION_ENUM_START(   RSDOS_OPTIONS_FTYPE, "ftype", "File type" )
584      OPTION_ENUM(   0,      "basic",      "Basic" )
585      OPTION_ENUM(   1,      "data",         "Data" )
586      OPTION_ENUM(   2,      "binary",      "Binary" )
587      OPTION_ENUM(   3,      "assembler",   "Assembler Source" )
588   OPTION_ENUM_END
589   OPTION_ENUM_START(   RSDOS_OPTIONS_ASCII, "ascii", "Ascii flag" )
590      OPTION_ENUM(   0,      "ascii",      "Ascii" )
591      OPTION_ENUM(   1,      "binary",      "Binary" )
592   OPTION_ENUM_END
593OPTION_GUIDE_END
594
595
596
597void rsdos_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
598{
599   switch(state)
600   {
601      /* --- the following bits of info are returned as 64-bit signed integers --- */
602      case IMGTOOLINFO_INT_PREFER_UCASE:               info->i = 1; break;
603      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(struct rsdos_direnum); break;
604
605      /* --- the following bits of info are returned as NULL-terminated strings --- */
606      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "rsdos"); break;
607      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "RS-DOS format"); break;
608      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
609      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
610      case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC:            strcpy(info->s = imgtool_temp_str(), "T0-[2]-3;M0-[1]"); break;
611
612      /* --- the following bits of info are returned as pointers to data or functions --- */
613      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
614      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = rsdos_diskimage_nextenum; break;
615      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = rsdos_diskimage_freespace; break;
616      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = rsdos_diskimage_readfile; break;
617      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = rsdos_diskimage_writefile; break;
618      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = rsdos_diskimage_deletefile; break;
619      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = rsdos_diskimage_suggesttransfer; break;
620      case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE:         info->writefile_optguide = coco_rsdos_writefile_optionguide; break;
621      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_coco; break;
622   }
623}
src/mess/tools/imgtool/concept.c
r1339r1340
1/*
2   Handlers for concept floppy images
3
4   Disk images are in MESS format.
5
6   Raphael Nabet, 2003
7*/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <limits.h>
13#include <assert.h>
14#include "osdepend.h"
15#include "imgtoolx.h"
16
17typedef struct UINT16xE
18{
19   UINT8 bytes[2];
20} UINT16xE;
21
22/*
23   get_UINT16xE
24
25   Read a 16-bit word, whether it is little-endian or big-endian
26
27   little_endian (I): non-zero if word is little-endian, zero if word is
28      big-endian
29   word (I): pointer to word to read
30
31   Returns value of word in native format
32*/
33INLINE UINT16 get_UINT16xE(int little_endian, UINT16xE word)
34{
35   return little_endian ? (word.bytes[0] | (word.bytes[1] << 8)) : ((word.bytes[0] << 8) | word.bytes[1]);
36}
37
38/*
39   set_UINT16xE
40
41   Write a 16-bit word, whether it is little-endian or big-endian
42
43   little_endian (I): non-zero if word is little-endian, zero if word is
44      big-endian
45   word (O): pointer to word to write
46   data (I): value to write in word, in native format
47*/
48INLINE void set_UINT16xE(int little_endian, UINT16xE *word, UINT16 data)
49{
50   if (little_endian)
51   {
52      word->bytes[0] = data & 0xff;
53      word->bytes[1] = (data >> 8) & 0xff;
54   }
55   else
56   {
57      word->bytes[0] = (data >> 8) & 0xff;
58      word->bytes[1] = data & 0xff;
59   }
60}
61
62/*
63   Disk structure:
64
65   Track 0 Sector 0 & 1: bootstrap loader
66   Track 0 Sector 2 through 5: disk directory
67   Remaining sectors are used for data.
68*/
69
70/*
71   device directory record (Disk sector 2-5)
72*/
73
74typedef struct concept_vol_hdr_entry
75{
76   UINT16xE   first_block;
77   UINT16xE   next_block;
78   UINT16xE   ftype;
79
80   unsigned char   volname[8];
81   UINT16xE   last_block;
82   UINT16xE   num_files;
83   UINT16xE   last_boot;
84   UINT16xE   last_access;
85   char      mem_flipped;
86   char      disk_flipped;
87   UINT16xE   unused;
88} concept_vol_hdr_entry;
89
90typedef struct concept_file_dir_entry
91{
92   UINT16xE   first_block;
93   UINT16xE   next_block;
94   UINT16xE   ftype;
95
96   unsigned char   filename[16];
97   UINT16xE   last_byte;
98   UINT16xE   last_access;
99} concept_file_dir_entry;
100
101typedef struct concept_dev_dir
102{
103   concept_vol_hdr_entry vol_hdr;
104   concept_file_dir_entry file_dir[77];
105   char unused[20];
106} concept_dev_dir;
107
108/*
109   concept disk image descriptor
110*/
111typedef struct concept_image
112{
113   imgtool_stream *file_handle;      /* imgtool file handle */
114   concept_dev_dir dev_dir;   /* cached copy of device directory */
115} concept_image;
116
117/*
118   concept catalog iterator, used when imgtool reads the catalog
119*/
120typedef struct concept_iterator
121{
122   concept_image *image;
123   int index;                     /* current index */
124} concept_iterator;
125
126
127static imgtoolerr_t concept_image_init(imgtool_image *img, imgtool_stream *f);
128static void concept_image_exit(imgtool_image *img);
129static void concept_image_info(imgtool_image *img, char *string, size_t len);
130static imgtoolerr_t concept_image_beginenum(imgtool_directory *enumeration, const char *path);
131static imgtoolerr_t concept_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
132static void concept_image_closeenum(imgtool_directory *enumeration);
133static imgtoolerr_t concept_image_freespace(imgtool_partition *partition, UINT64 *size);
134static imgtoolerr_t concept_image_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf);
135/*static imgtoolerr_t concept_image_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions);
136static imgtoolerr_t concept_image_deletefile(imgtool_partition *partition, const char *filename);
137static imgtoolerr_t concept_image_create(const imgtool_module *mod, imgtool_stream *f, option_resolution *createoptions);*/
138
139void concept_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
140{
141   switch(state)
142   {
143      /* --- the following bits of info are returned as 64-bit signed integers --- */
144      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(concept_image); break;
145      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(concept_iterator); break;
146
147      /* --- the following bits of info are returned as NULL-terminated strings --- */
148      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "concept"); break;
149      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "Concept floppy disk image"); break;
150      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "img"); break;
151      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
152
153      /* --- the following bits of info are returned as pointers to data or functions --- */
154      case IMGTOOLINFO_PTR_OPEN:                     info->open = concept_image_init; break;
155      case IMGTOOLINFO_PTR_CLOSE:                     info->close = concept_image_exit; break;
156      case IMGTOOLINFO_PTR_INFO:                     info->info = concept_image_info; break;
157      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = concept_image_beginenum; break;
158      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = concept_image_nextenum; break;
159      case IMGTOOLINFO_PTR_CLOSE_ENUM:               info->close_enum = concept_image_closeenum; break;
160      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = concept_image_freespace; break;
161      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = concept_image_readfile; break;
162      case IMGTOOLINFO_PTR_WRITE_FILE:               /* info->write_file = concept_image_writefile */; break;
163      case IMGTOOLINFO_PTR_DELETE_FILE:               /* info->delete_file = concept_image_deletefile */; break;
164      case IMGTOOLINFO_PTR_CREATE:                  /* info->create = concept_image_create */; break;
165   }
166}
167
168/*
169   read_physical_record
170
171   Read one 512-byte physical record from a disk image
172
173   file_handle: imgtool file handle
174   secnum: physical record address
175   dest: pointer to destination buffer
176
177   Return non-zero on error
178*/
179static int read_physical_record(imgtool_stream *file_handle, int secnum, void *dest)
180{
181   int reply;
182
183   /* seek to sector */
184   reply = stream_seek(file_handle, secnum*512, SEEK_SET);
185   if (reply)
186      return 1;
187   /* read it */
188   reply = stream_read(file_handle, dest, 512);
189   if (reply != 512)
190      return 1;
191
192   return 0;
193}
194
195#ifdef UNUSED_FUNCTION
196/*
197   write_physical_record
198
199   Write one 512-byte physical record to a disk image
200
201   file_handle: imgtool file handle
202   secnum: logical sector address
203   src: pointer to source buffer
204
205   Return non-zero on error
206*/
207static int write_physical_record(imgtool_stream *file_handle, int secnum, const void *src)
208{
209   int reply;
210
211   /* seek to sector */
212   reply = stream_seek(file_handle, secnum*512, SEEK_SET);
213   if (reply)
214      return 1;
215   /* read it */
216   reply = stream_write(file_handle, src, 512);
217   if (reply != 512)
218      return 1;
219
220   return 0;
221}
222#endif
223
224/*
225   Search for a file name on a concept_image
226
227   image (I): image reference
228   filename (I): name of the file to search
229   entry_index (O): index of file in disk catalog
230
231   Return non-zero on error
232*/
233static int get_catalog_entry(concept_image *image, const unsigned char *filename, int *entry_index)
234{
235   int filename_len = filename[0];
236   int i;
237
238   if (filename_len > 15)
239      /* file name is bad */
240      return 1;
241
242   for (i = 0; i < 77; i++)
243   {
244      if (!memcmp(filename, image->dev_dir.file_dir[i].filename, filename_len+1))
245      {
246         /* file found */
247         *entry_index = i;
248         return 0;
249      }
250   }
251
252   /* file not found */
253   return 1;
254}
255
256/*
257   Open a file as a concept_image.
258*/
259static imgtoolerr_t concept_image_init(imgtool_image *img, imgtool_stream *f)
260{
261   concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);
262   int reply;
263   int i;
264   unsigned totphysrecs;
265
266   image->file_handle = f;
267
268   /* read device directory */
269   for (i=0; i<4; i++)
270   {
271      reply = read_physical_record(f, i+2, ((char *) & image->dev_dir)+i*512);
272      if (reply)
273         return IMGTOOLERR_READERROR;
274   }
275
276   /* do primitive checks */
277   totphysrecs = get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.last_block)
278               - get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.first_block);
279
280   if ((get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.first_block) != 0)
281      || (get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.next_block) != 6)
282      || (totphysrecs < 6) /*|| (stream_size(f) != totphysrecs*512)*/
283      || (image->dev_dir.vol_hdr.volname[0] > 7))
284   {
285      return IMGTOOLERR_CORRUPTIMAGE;
286   }
287
288   return IMGTOOLERR_SUCCESS;
289}
290
291/*
292   close a concept_image
293*/
294static void concept_image_exit(imgtool_image *img)
295{
296   /*concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);*/
297}
298
299/*
300   get basic information on a concept_image
301
302   Currently returns the volume name
303*/
304static void concept_image_info(imgtool_image *img, char *string, size_t len)
305{
306   concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);
307   char vol_name[8];
308
309   memcpy(vol_name, image->dev_dir.vol_hdr.volname + 1, image->dev_dir.vol_hdr.volname[0]);
310   vol_name[image->dev_dir.vol_hdr.volname[0]] = 0;
311
312   snprintf(string, len, "%s", vol_name);
313}
314
315/*
316   Open the disk catalog for enumeration
317*/
318static imgtoolerr_t concept_image_beginenum(imgtool_directory *enumeration, const char *path)
319{
320   concept_iterator *iter;
321
322   iter = (concept_iterator *) imgtool_directory_extrabytes(enumeration);
323   iter->image = (concept_image *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
324   iter->index = 0;
325   return IMGTOOLERR_SUCCESS;
326}
327
328/*
329   Enumerate disk catalog next entry
330*/
331static imgtoolerr_t concept_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
332{
333   concept_iterator *iter = (concept_iterator *) imgtool_directory_extrabytes(enumeration);
334
335
336   ent->corrupt = 0;
337   ent->eof = 0;
338
339   if ((iter->image->dev_dir.file_dir[iter->index].filename[0] == 0) || (iter->index > 77))
340   {
341      ent->eof = 1;
342   }
343   else if (iter->image->dev_dir.file_dir[iter->index].filename[0] > 15)
344   {
345      ent->corrupt = 1;
346   }
347   else
348   {
349      int len = iter->image->dev_dir.file_dir[iter->index].filename[0];
350      const char *type;
351
352      if (len > sizeof(ent->filename) / sizeof(ent->filename[0]))
353         len = sizeof(ent->filename) / sizeof(ent->filename[0]);
354      memcpy(ent->filename, iter->image->dev_dir.file_dir[iter->index].filename + 1, len);
355      ent->filename[len] = 0;
356
357      /* parse flags */
358      switch (get_UINT16xE(iter->image->dev_dir.vol_hdr.disk_flipped, iter->image->dev_dir.file_dir[iter->index].ftype) & 0xf)
359      {
360      case 0:
361      case 8:
362         type = "DIRHDR";
363         break;
364      case 2:
365         type = "CODE";
366         break;
367      case 3:
368         type = "TEXT";
369         break;
370      case 5:
371         type = "DATA";
372         break;
373      default:
374         type = "???";
375         break;
376      }
377      snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%s", type);
378
379      /* len in physrecs */
380      ent->filesize = get_UINT16xE(iter->image->dev_dir.vol_hdr.disk_flipped, iter->image->dev_dir.file_dir[iter->index].next_block)
381                     - get_UINT16xE(iter->image->dev_dir.vol_hdr.disk_flipped, iter->image->dev_dir.file_dir[iter->index].first_block);
382
383      iter->index++;
384   }
385
386   return 0;
387}
388
389/*
390   Free enumerator
391*/
392static void concept_image_closeenum(imgtool_directory *enumeration)
393{
394}
395
396/*
397   Compute free space on disk image
398*/
399static imgtoolerr_t concept_image_freespace(imgtool_partition *partition, UINT64 *size)
400{
401   imgtool_image *img = imgtool_partition_image(partition);
402   concept_image *image = (concept_image*) img;
403   int free_blocks;
404   int i;
405
406   /* first get number of data blocks */
407   free_blocks = get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.last_block)
408               - get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.next_block);
409
410   /* next substract lenght of each file */
411   for (i=0; (image->dev_dir.file_dir[i].filename[0] != 0) && (i <= 77); i++)
412   {
413      free_blocks -= get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[i].next_block)
414                  - get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[i].first_block);
415   }
416
417   *size = free_blocks;
418
419   return IMGTOOLERR_SUCCESS;
420}
421
422/*
423   Extract a file from a concept_image.
424*/
425static imgtoolerr_t concept_image_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
426{
427   imgtool_image *img = imgtool_partition_image(partition);
428   concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);
429   size_t filename_len = strlen(filename);
430   unsigned char concept_fname[16];
431   int catalog_index;
432   int i;
433   UINT8 buf[512];
434
435   if (filename_len > 15)
436      return IMGTOOLERR_BADFILENAME;
437
438   concept_fname[0] = filename_len;
439   memcpy(concept_fname+1, filename, filename_len);
440
441   if (get_catalog_entry(image, concept_fname, &catalog_index))
442      return IMGTOOLERR_FILENOTFOUND;
443
444   for (i = get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[catalog_index].first_block);
445         i < get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[catalog_index].next_block);
446         i++)
447   {
448      if (read_physical_record(image->file_handle, i, buf))
449         return IMGTOOLERR_READERROR;
450
451      if (stream_write(destf, buf, 512) != 512)
452         return IMGTOOLERR_WRITEERROR;
453   }
454
455   return 0;
456}
457
458#if 0
459/*
460   Add a file to a concept_image.
461*/
462static imgtoolerr_t concept_image_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
463{
464   /* ... */
465
466   return 0;
467}
468
469/*
470   Delete a file from a concept_image.
471*/
472static imgtoolerr_t concept_image_deletefile(imgtool_partition *partition, const char *filename)
473{
474   /* ... */
475
476   return 0;
477}
478
479/*
480   Create a blank concept_image.
481*/
482static imgtoolerr_t concept_image_create(const imgtool_module *mod, imgtool_stream *f, option_resolution *createoptions)
483{
484   /* ... */
485
486   return 0;
487}
488#endif
src/mess/tools/imgtool/xsa.c
r1339r1340
1/*
2 * xsa.c : decompresses XelaSoft Archives.
3 *
4 * Sean Young
5 */
6
7#include "osdepend.h"
8#include "imgtoolx.h"
9#include "utils.h"
10
11
12typedef struct {
13   imgtool_image         base;
14   char         *file_name;
15   imgtool_stream          *file_handle;
16   int          size;
17   } XSA_IMAGE;
18
19typedef struct
20   {
21   imgtool_directory    base;
22   XSA_IMAGE   *image;
23   int         index;
24   } XSA_ITERATOR;
25
26static int xsa_extract (imgtool_stream *in, imgtool_stream *out);
27static int xsa_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
28static void xsa_image_exit(imgtool_image *img);
29static int xsa_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
30static int xsa_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
31static void xsa_image_closeenum(imgtool_directory *enumeration);
32static int xsa_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
33
34IMAGEMODULE(
35   xsa,
36   "XelaSoft Archive",            /* human readable name */
37   "xsa",                     /* file extension */
38   NULL,                     /* crcfile */
39   NULL,                     /* crc system name */
40   NULL,                     /* eoln */
41   0,                        /* flags */
42   xsa_image_init,               /* init function */
43   xsa_image_exit,               /* exit function */
44   NULL,                     /* info function */
45   xsa_image_beginenum,         /* begin enumeration */
46   xsa_image_nextenum,            /* enumerate next */
47   xsa_image_closeenum,         /* close enumeration */
48   NULL,                     /* free space on image */
49   xsa_image_readfile,            /* read file */
50   NULL,                     /* write file */
51   NULL,                     /* delete file */
52   NULL,                     /* create image */
53   NULL,                     /* read sector */
54   NULL,                     /* write sector */
55   NULL,                     /* file options */
56   NULL                     /* create options */
57)
58
59static int xsa_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
60   {
61   XSA_IMAGE *image;
62   int pos, len, size;
63    UINT8 header[4], byt;
64   char *file_name, *file_name_new;
65
66   size = stream_size (f);
67   if (size < 5) return IMGTOOLERR_MODULENOTFOUND;
68   if (4 != stream_read (f, header, 4) ) return IMGTOOLERR_READERROR;
69   
70    if (memcmp (header, "PCK\010", 4) )
71      return IMGTOOLERR_MODULENOTFOUND;
72   
73   if (4 != stream_read (f, &size, 4) ) return IMGTOOLERR_READERROR;
74   size = LITTLE_ENDIANIZE_INT32 (size);
75   if (4 != stream_read (f, header, 4) ) return IMGTOOLERR_READERROR;
76   
77   /* get name from XSA header, can't be longer than 8.3 really */
78   /* but could be, it's zero-terminated */
79   file_name = NULL;
80   pos = len = 0;
81   while (1)
82      {
83      if (1 != stream_read (f, &byt, 1) )
84         {
85         if (file_name) free (file_name);
86         *outimg=NULL;
87         return IMGTOOLERR_READERROR;
88         }
89      if (len <= pos)
90         {
91         len += 8; /* why 8? */
92         file_name_new = realloc (file_name, len);
93         if (!file_name_new)
94            {
95            if (file_name) free (file_name);
96            *outimg=NULL;
97            return IMGTOOLERR_OUTOFMEMORY;
98            }
99         file_name = file_name_new;
100         }
101      file_name[pos++] = byt;
102      if (!byt) break;
103      }
104
105   image = (XSA_IMAGE*)malloc (sizeof (XSA_IMAGE) );
106   if (!image) return IMGTOOLERR_OUTOFMEMORY;
107   *outimg = (imgtool_image*)image;
108
109   memset(image, 0, sizeof(XSA_IMAGE));
110   image->base.module = mod;
111   image->file_handle = f;
112   image->size = size;
113   image->file_name = file_name;
114
115   return 0;
116   }
117
118static void xsa_image_exit(imgtool_image *img)
119   {
120   XSA_IMAGE *image=(XSA_IMAGE*)img;
121   stream_close(image->file_handle);
122   free(image->file_name);
123   free(image);
124   }
125
126static int xsa_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
127   {
128   XSA_IMAGE *image=(XSA_IMAGE*)img;
129   XSA_ITERATOR *iter;
130
131   iter=*(XSA_ITERATOR**)outenum = (XSA_ITERATOR*) malloc(sizeof(XSA_ITERATOR));
132   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
133
134   iter->base.module = img->module;
135
136   iter->image=image;
137   iter->index = 0;
138   return 0;
139   }
140
141static int xsa_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
142   {
143   XSA_ITERATOR *iter=(XSA_ITERATOR*)enumeration;
144
145   ent->eof = iter->index;
146   if (!ent->eof)
147      {
148      strcpy (ent->fname, iter->image->file_name);
149
150      ent->corrupt=0;
151      ent->filesize = iter->image->size;
152
153      iter->index++;
154      }
155
156   return 0;
157   }
158
159static void xsa_image_closeenum(imgtool_directory *enumeration)
160   {
161   free(enumeration);
162   }
163
164static int xsa_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
165   {
166   XSA_IMAGE *image=(XSA_IMAGE*)img;
167
168   /*  check file name */
169   if (mame_stricmp (fname, image->file_name) )
170      return IMGTOOLERR_MODULENOTFOUND;
171
172   return xsa_extract (image->file_handle, destf);
173   }
174
175
176/*
177 * .xsa decompression. Code stolen from :
178 *
179 * http://web.inter.nl.net/users/A.P.Wulms/
180 */
181
182
183/****************************************************************/
184/* LZ77 data decompression                              */
185/* Copyright (c) 1994 by XelaSoft                        */
186/* version history:                                    */
187/*   version 0.9, start date: 11-27-1994                  */
188/****************************************************************/
189
190#define SHORT unsigned
191
192#define slwinsnrbits (13)
193#define maxstrlen (254)
194
195#define maxhufcnt (127)
196#define logtblsize (4)
197
198
199#define tblsize (1<<logtblsize)
200
201typedef struct huf_node {
202  SHORT weight;
203  struct huf_node *child1, *child2;
204} huf_node;
205
206/****************************************************************/
207/* global vars                                       */
208/****************************************************************/
209static unsigned updhufcnt;
210static unsigned cpdist[tblsize+1];
211static unsigned cpdbmask[tblsize];
212static unsigned cpdext[] = { /* Extra bits for distance codes */
213          0,  0,  0,  0,  1,  2,  3,  4,
214          5,  6,  7,  8,  9, 10, 11, 12};
215
216static SHORT tblsizes[tblsize];
217static huf_node huftbl[2*tblsize-1];
218
219/****************************************************************/
220/* maak de huffman codeer informatie                     */
221/****************************************************************/
222static void mkhuftbl( void )
223{
224  unsigned count;
225  huf_node  *hufpos;
226  huf_node  *l1pos, *l2pos;
227  SHORT tempw;
228
229  /* Initialize the huffman tree */
230  for (count=0, hufpos=huftbl; count != tblsize; count++) {
231    (hufpos++)->weight=1+(tblsizes[count] >>= 1);
232  }
233  for (count=tblsize; count != 2*tblsize-1; count++)
234    (hufpos++)->weight=-1;
235
236  /* Place the nodes in the correct manner in the tree */
237  while (huftbl[2*tblsize-2].weight == -1) {
238    for (hufpos=huftbl; !(hufpos->weight); hufpos++)
239      ;
240    l1pos = hufpos++;
241    while (!(hufpos->weight))
242      hufpos++;
243    if (hufpos->weight < l1pos->weight) {
244      l2pos = l1pos;
245      l1pos = hufpos++;
246    }
247    else
248      l2pos = hufpos++;
249    while ((tempw=(hufpos)->weight) != -1) {
250      if (tempw) {
251        if (tempw < l1pos->weight) {
252          l2pos = l1pos;
253          l1pos = hufpos;
254        }
255        else if (tempw < l2pos->weight)
256          l2pos = hufpos;
257      }
258      hufpos++;
259    }
260    hufpos->weight = l1pos->weight+l2pos->weight;
261    (hufpos->child1 = l1pos)->weight = 0;
262    (hufpos->child2 = l2pos)->weight = 0;
263  }
264  updhufcnt = maxhufcnt;
265}
266
267/****************************************************************/
268/* initialize the huffman info tables                           */
269/****************************************************************/
270static void inithufinfo( void )
271{
272  unsigned offs, count;
273
274  for (offs=1, count=0; count != tblsize; count++) {
275    cpdist[count] = offs;
276    offs += (cpdbmask[count] = 1<<cpdext[count]);
277  }
278  cpdist[count] = offs;
279
280  for (count = 0; count != tblsize; count++) {
281    tblsizes[count] = 0; /* reset the table counters */
282    huftbl[count].child1 = 0;  /* mark the leave nodes */
283  }
284  mkhuftbl(); /* make the huffman table */
285}
286
287/****************************************************************/
288/* global vars                                       */
289/****************************************************************/
290static imgtool_stream *in_stream, *out_stream;
291
292static UINT8 *outbuf;       /* the output buffer     */
293static UINT8 *outbufpos;    /* pos in output buffer  */
294static int outbufcnt;  /* #elements in the output buffer */
295static int error_occ;
296
297static UINT8 bitflg;  /* flag with the bits */
298static UINT8 bitcnt;  /* #resterende bits   */
299
300#define slwinsize (1 << slwinsnrbits)
301#define outbufsize (slwinsize+4096)
302
303/****************************************************************/
304/* The function prototypes                              */
305/****************************************************************/
306static void unlz77( void );       /* perform the real decompression       */
307static void charout(UINT8);      /* put a character in the output stream */
308static unsigned rdstrlen( void ); /* read string length                   */
309static unsigned rdstrpos( void ); /* read string pos                      */
310static void flushoutbuf( void );
311static UINT8 charin( void );       /* read a char                          */
312static UINT8 bitin( void );        /* read a bit                           */
313
314/****************************************************************/
315/* de hoofdlus                                       */
316/****************************************************************/
317static int xsa_extract (imgtool_stream *in, imgtool_stream *out)
318    {
319    UINT8 byt;
320
321   /* setup the in-stream */
322   stream_seek (in, 12, SEEK_SET);
323    do  {
324      if (1 != stream_read (in, &byt, 1) )
325         return IMGTOOLERR_READERROR;
326      } while (byt);
327   in_stream = in;
328    bitcnt = 0;         /* nog geen bits gelezen               */
329
330   /* setup the out buffer */
331    outbuf = malloc (outbufsize);
332    if (!outbuf) return IMGTOOLERR_OUTOFMEMORY;
333    outbufcnt = 0;
334    outbufpos = outbuf; /* dadelijk vooraan in laden           */
335   out_stream = out;
336
337   /* let's do it .. */
338   inithufinfo(); /* initialize the cpdist tables */
339
340    error_occ = 0;
341    unlz77();         /* decrunch de data echt               */
342
343   free (outbuf);
344
345   return error_occ;
346    }
347
348/****************************************************************/
349/* the actual decompression algorithm itself               */
350/****************************************************************/
351static void unlz77( void )
352{
353  UINT8 strl = 0;
354  unsigned strpos;
355
356  do {
357    switch (bitin()) {
358      case 0 : charout(charin()); break;
359      case 1 : strl = rdstrlen();
360          if (strl == (maxstrlen+1))
361       break;
362          strpos = rdstrpos();
363          while (strl--)
364       charout(*(outbufpos-strpos));
365          strl = 0;
366          break;
367    }
368  }
369  while (strl != (maxstrlen+1)&&!error_occ);
370  flushoutbuf ();
371}
372
373/****************************************************************/
374/* Put the next character in the input buffer.                  */
375/* Take care that minimal 'slwinsize' chars are before the      */
376/* current position.                                            */
377/****************************************************************/
378static void charout(UINT8 ch)
379{
380  if (error_occ) return;
381
382  if ((outbufcnt++) == outbufsize) {
383    if ( (outbufsize-slwinsize) != stream_write (out_stream, outbuf, outbufsize-slwinsize) )
384       error_occ = IMGTOOLERR_WRITEERROR;
385
386    memcpy(outbuf, outbuf+outbufsize-slwinsize, slwinsize);
387    outbufpos = outbuf+slwinsize;
388    outbufcnt = slwinsize+1;
389  }
390  *(outbufpos++) = ch;
391}
392
393/****************************************************************/
394/* flush the output buffer                                      */
395/****************************************************************/
396static void flushoutbuf( void )
397{
398  if (!error_occ && outbufcnt) {
399    if (outbufcnt != stream_write (out_stream, outbuf, outbufcnt) )
400      error_occ = IMGTOOLERR_WRITEERROR;
401
402    outbufcnt = 0;
403  }
404}
405
406/****************************************************************/
407/* read string length                                 */
408/****************************************************************/
409static unsigned rdstrlen( void )
410{
411  UINT8 len;
412  UINT8 nrbits;
413
414  if (!bitin())
415    return 2;
416  if (!bitin())
417    return 3;
418  if (!bitin())
419    return 4;
420
421  for (nrbits = 2; (nrbits != 7) && bitin(); nrbits++)
422    ;
423
424  len = 1;
425  while (nrbits--)
426    len = (len << 1) | bitin();
427
428  return (unsigned)(len+1);
429}
430
431/****************************************************************/
432/* read string pos                                    */
433/****************************************************************/
434static unsigned rdstrpos( void )
435{
436  UINT8 nrbits;
437  UINT8 cpdindex;
438  unsigned strpos;
439  huf_node *hufpos;
440
441  hufpos = huftbl+2*tblsize-2;
442
443  while (hufpos->child1)
444    if (bitin()) {
445      hufpos = hufpos->child2;
446    }
447    else {
448      hufpos = hufpos->child1;
449    }
450  cpdindex = hufpos-huftbl;
451  tblsizes[cpdindex]++;
452
453  if (cpdbmask[cpdindex] >= 256) {
454    UINT8 strposmsb, strposlsb;
455
456    strposlsb = (unsigned)charin();  /* lees LSB van strpos */
457    strposmsb = 0;
458    for (nrbits = cpdext[cpdindex]-8; nrbits--; strposmsb |= bitin())
459      strposmsb <<= 1;
460    strpos = (unsigned)strposlsb | (((unsigned)strposmsb)<<8);
461  }
462  else {
463    strpos=0;
464    for (nrbits = cpdext[cpdindex]; nrbits--; strpos |= bitin())
465      strpos <<= 1;
466  }
467  if (!(updhufcnt--))
468    mkhuftbl(); /* make the huffman table */
469
470  return strpos+cpdist[cpdindex];
471}
472
473/****************************************************************/
474/* read a bit from the input file                        */
475/****************************************************************/
476static UINT8 bitin( void )
477{
478  UINT8 temp;
479
480  if (!bitcnt) {
481    bitflg = charin();  /* lees de bitflg in */
482    bitcnt = 8;         /* nog 8 bits te verwerken */
483  }
484  temp = bitflg & 1;
485  bitcnt--;  /* weer 1 bit verwerkt */
486  bitflg >>= 1;
487
488  return temp;
489}
490
491/****************************************************************/
492/* Get the next character from the input buffer.                */
493/****************************************************************/
494static UINT8 charin( void )
495   {
496   UINT8 byte;
497
498   if (error_occ)
499      return 0;
500   else
501        {
502      if (1 != stream_read (in_stream, &byte, 1) )
503         {
504         error_occ = IMGTOOLERR_READERROR;
505         return 0;
506         }
507      else
508         return byte;
509      }
510   }
src/mess/tools/imgtool/imgtool.mak
r1339r1340
77###########################################################################
88
99
10# Add path to imgtool headers
11CFLAGS += \
12   -I$(SRC)/$(TARGET)/tools/imgtool \
13
14
15# Imgtool directories
16IMGTOOLOBJ = $(MESSOBJ)/tools/imgtool
17IMGTOOL_MODULES = $(IMGTOOLOBJ)/modules
18
1019OBJDIRS += \
11   $(MESSOBJ)/tools/imgtool
20   $(IMGTOOLOBJ) \
21   $(IMGTOOL_MODULES)
1222
1323
14IMGTOOL_LIB_OBJS =                     \
15   $(OBJ)/emu/mamecore.o               \
16   $(OBJ)/version.o                  \
17   $(OBJ)/mess/tagpool.o               \
18   $(OBJ)/mess/utils.o                  \
19   $(OBJ)/mess/tagpool.o               \
20   $(OBJ)/mess/opresolv.o               \
21   $(OBJ)/mess/formats/ioprocs.o         \
22   $(OBJ)/mess/formats/flopimg.o         \
23   $(OBJ)/mess/formats/cassimg.o         \
24   $(OBJ)/mess/formats/basicdsk.o         \
25   $(OBJ)/mess/formats/coco_dsk.o         \
26   $(OBJ)/mess/formats/coco_cas.o         \
27   $(OBJ)/mess/formats/pc_dsk.o         \
28   $(OBJ)/mess/formats/ap2_dsk.o         \
29   $(OBJ)/mess/formats/ap_dsk35.o         \
30   $(OBJ)/mess/formats/wavfile.o         \
31   $(OBJ)/mess/formats/vt_dsk.o         \
32   $(OBJ)/mess/tools/imgtool/stream.o      \
33   $(OBJ)/mess/tools/imgtool/library.o      \
34   $(OBJ)/mess/tools/imgtool/modules.o      \
35   $(OBJ)/mess/tools/imgtool/iflopimg.o   \
36   $(OBJ)/mess/tools/imgtool/filter.o      \
37   $(OBJ)/mess/tools/imgtool/filteoln.o   \
38   $(OBJ)/mess/tools/imgtool/filtbas.o      \
39   $(OBJ)/mess/tools/imgtool/macbin.o      \
40   $(OBJ)/mess/tools/imgtool/imgtool.o      \
41   $(OBJ)/mess/tools/imgtool/imgterrs.o   \
42   $(OBJ)/mess/tools/imgtool/rsdos.o      \
43   $(OBJ)/mess/tools/imgtool/os9.o         \
44   $(OBJ)/mess/tools/imgtool/imghd.o      \
45   $(OBJ)/mess/tools/imgtool/mac.o         \
46   $(OBJ)/mess/tools/imgtool/ti99.o      \
47   $(OBJ)/mess/tools/imgtool/ti990hd.o      \
48   $(OBJ)/mess/tools/imgtool/concept.o      \
49   $(OBJ)/mess/tools/imgtool/fat.o         \
50   $(OBJ)/mess/tools/imgtool/pc_flop.o      \
51   $(OBJ)/mess/tools/imgtool/pc_hard.o      \
52   $(OBJ)/mess/tools/imgtool/prodos.o      \
53   $(OBJ)/mess/tools/imgtool/vzdos.o      \
54   $(OBJ)/mess/tools/imgtool/thomson.o      \
55   $(OBJ)/mess/tools/imgtool/macutil.o      \
56   $(OBJ)/mess/tools/imgtool/cybiko.o
57#     $(OBJ)/mess/tools/imgtool/tstsuite.o \
58#     $(OBJ)/mess/formats/fmsx_cas.o       \
59#     $(OBJ)/mess/formats/svi_cas.o        \
60#     $(OBJ)/mess/formats/ti85_ser.o       \
61#     $(OBJ)/mess/tools/imgtool/imgfile.o  \
62#     $(OBJ)/mess/tools/imgtool/imgwave.o  \
63#     $(OBJ)/mess/tools/imgtool/cococas.o  \
64#     $(OBJ)/mess/tools/imgtool/vmsx_tap.o \
65#     $(OBJ)/mess/tools/imgtool/vmsx_gm2.o \
66#     $(OBJ)/mess/tools/imgtool/fmsx_cas.o \
67#     $(OBJ)/mess/tools/imgtool/svi_cas.o  \
68#     $(OBJ)/mess/tools/imgtool/msx_dsk.o  \
69#     $(OBJ)/mess/tools/imgtool/xsa.o      \
70#     $(OBJ)/mess/tools/imgtool/t64.o      \
71#     $(OBJ)/mess/tools/imgtool/lynx.o     \
72#     $(OBJ)/mess/tools/imgtool/crt.o      \
73#     $(OBJ)/mess/tools/imgtool/d64.o      \
74#     $(OBJ)/mess/tools/imgtool/rom16.o    \
75#     $(OBJ)/mess/tools/imgtool/nccard.o   \
76#     $(OBJ)/mess/tools/imgtool/ti85.o     \
24# Imgtool shared objects
25IMGTOOL_LIB_OBJS =                  \
26   $(OBJ)/version.o               \
27   $(EMUOBJ)/mamecore.o            \
28   $(MESSOBJ)/tagpool.o            \
29   $(MESSOBJ)/utils.o               \
30   $(MESSOBJ)/tagpool.o            \
31   $(MESSOBJ)/opresolv.o            \
32   $(MESS_FORMATS)/ioprocs.o         \
33   $(MESS_FORMATS)/flopimg.o         \
34   $(MESS_FORMATS)/cassimg.o         \
35   $(MESS_FORMATS)/basicdsk.o         \
36   $(MESS_FORMATS)/coco_dsk.o         \
37   $(MESS_FORMATS)/coco_cas.o         \
38   $(MESS_FORMATS)/pc_dsk.o         \
39   $(MESS_FORMATS)/ap2_dsk.o         \
40   $(MESS_FORMATS)/ap_dsk35.o         \
41   $(MESS_FORMATS)/wavfile.o         \
42   $(MESS_FORMATS)/vt_dsk.o         \
43   $(IMGTOOLOBJ)/stream.o            \
44   $(IMGTOOLOBJ)/library.o            \
45   $(IMGTOOLOBJ)/modules.o            \
46   $(IMGTOOLOBJ)/iflopimg.o         \
47   $(IMGTOOLOBJ)/filter.o            \
48   $(IMGTOOLOBJ)/filteoln.o         \
49   $(IMGTOOLOBJ)/filtbas.o            \
50   $(IMGTOOLOBJ)/imgtool.o            \
51   $(IMGTOOLOBJ)/imgterrs.o         \
52   $(IMGTOOLOBJ)/imghd.o            \
53   $(IMGTOOL_MODULES)/macbin.o         \
54   $(IMGTOOL_MODULES)/rsdos.o         \
55   $(IMGTOOL_MODULES)/os9.o         \
56   $(IMGTOOL_MODULES)/mac.o         \
57   $(IMGTOOL_MODULES)/ti99.o         \
58   $(IMGTOOL_MODULES)/ti990hd.o      \
59   $(IMGTOOL_MODULES)/concept.o      \
60   $(IMGTOOL_MODULES)/fat.o         \
61   $(IMGTOOL_MODULES)/pc_flop.o      \
62   $(IMGTOOL_MODULES)/pc_hard.o      \
63   $(IMGTOOL_MODULES)/prodos.o         \
64   $(IMGTOOL_MODULES)/vzdos.o         \
65   $(IMGTOOL_MODULES)/thomson.o      \
66   $(IMGTOOL_MODULES)/macutil.o      \
67   $(IMGTOOL_MODULES)/cybiko.o
68#   $(IMGTOOLOBJ)/tstsuite.o         \
69#   $(IMGTOOLOBJ)/imgfile.o            \
70#   $(IMGTOOLOBJ)/imgwave.o            \
71#   $(MESS_FORMATS)/fmsx_cas.o         \
72#   $(MESS_FORMATS)/svi_cas.o         \
73#   $(MESS_FORMATS)/ti85_ser.o         \
74#   $(IMGTOOL_MODULES)/cococas.o      \
75#   $(IMGTOOL_MODULES)/vmsx_tap.o      \
76#   $(IMGTOOL_MODULES)/vmsx_gm2.o      \
77#   $(IMGTOOL_MODULES)/fmsx_cas.o      \
78#   $(IMGTOOL_MODULES)/svi_cas.o      \
79#   $(IMGTOOL_MODULES)/msx_dsk.o      \
80#   $(IMGTOOL_MODULES)/xsa.o         \
81#   $(IMGTOOL_MODULES)/t64.o         \
82#   $(IMGTOOL_MODULES)/lynx.o         \
83#   $(IMGTOOL_MODULES)/crt.o         \
84#   $(IMGTOOL_MODULES)/d64.o         \
85#   $(IMGTOOL_MODULES)/rom16.o         \
86#   $(IMGTOOL_MODULES)/nccard.o         \
87#   $(IMGTOOL_MODULES)/ti85.o         \
7788
7889
7990
r1339r1340
8394
8495IMGTOOL_OBJS = \
8596   $(IMGTOOL_LIB_OBJS) \
86   $(OBJ)/mess/tools/imgtool/main.o \
87   $(OBJ)/mess/tools/imgtool/stubs.o \
88   $(OBJ)/mess/toolerr.o
97   $(IMGTOOLOBJ)/main.o \
98   $(IMGTOOLOBJ)/stubs.o \
99   $(MESSOBJ)/toolerr.o
89100   
90101imgtool-bin: maketree imgtool$(EXE)
91102
src/mess/tools/imgtool/modules/macutil.c
r0r1340
1/****************************************************************************
2
3   macutil.c
4
5   Imgtool Utility code for manipulating certain Apple/Mac data structures
6   and conventions
7
8*****************************************************************************/
9
10#include "macutil.h"
11
12
13time_t mac_crack_time(UINT32 t)
14{
15   /* not sure if this is correct... */
16   return t - (((1970 - 1904) * 365) + 17) * 24 * 60 * 60;
17}
18
19
20
21UINT32 mac_setup_time(time_t t)
22{
23   /* not sure if this is correct... */
24   return t + (((1970 - 1904) * 365) + 17) * 24 * 60 * 60;
25}
26
27
28
29UINT32 mac_time_now(void)
30{
31   time_t now;
32   time(&now);
33   return mac_setup_time(now);
34}
35
36
37
38imgtoolerr_t mac_identify_fork(const char *fork_string, mac_fork_t *fork_num)
39{
40   if (!strcmp(fork_string, ""))
41      *fork_num = MAC_FORK_DATA;
42   else if (!strcmp(fork_string, "RESOURCE_FORK"))
43      *fork_num = MAC_FORK_RESOURCE;
44   else
45      return IMGTOOLERR_FORKNOTFOUND;
46   return IMGTOOLERR_SUCCESS;
47}
48
49
50
51void mac_suggest_transfer(mac_filecategory_t file_category, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
52{
53   suggestions[0].viability = (file_category == MAC_FILECATEGORY_FORKED) ? SUGGESTION_RECOMMENDED : SUGGESTION_POSSIBLE;
54   suggestions[0].filter = filter_macbinary_getinfo;
55   suggestions[0].fork = NULL;
56   suggestions[0].description = NULL;
57
58   suggestions[1].viability = (file_category == MAC_FILECATEGORY_TEXT) ? SUGGESTION_RECOMMENDED : SUGGESTION_POSSIBLE;
59   suggestions[1].filter = filter_eoln_getinfo;
60   suggestions[1].fork = NULL;
61   suggestions[1].description = NULL;
62
63   suggestions[2].viability = (file_category == MAC_FILECATEGORY_DATA) ? SUGGESTION_RECOMMENDED : SUGGESTION_POSSIBLE;
64   suggestions[2].filter = NULL;
65   suggestions[2].fork = "";
66   suggestions[2].description = "Raw (data fork)";
67
68   suggestions[3].viability = SUGGESTION_POSSIBLE;
69   suggestions[3].filter = NULL;
70   suggestions[3].fork = "RESOURCE_FORK";
71   suggestions[3].description = "Raw (resource fork)";
72}
73
74
75
76void pascal_from_c_string(unsigned char *pstring, size_t pstring_len, const char *cstring)
77{
78   size_t cstring_len, i;
79
80   cstring_len = strlen(cstring);
81   pstring[0] = MIN(cstring_len, pstring_len - 1);
82
83   for (i = 0; i < pstring[0]; i++)
84      pstring[1 + i] = cstring[i];
85   while(i < pstring_len - 1)
86      pstring[1 + i++] = '\0';
87}
88
src/mess/tools/imgtool/modules/ti99.c
r0r1340
1/*
2   Handlers for ti99 disk images
3
4   We support the following types of image:
5   * floppy disks ("DSK format") in v9t9, pc99 and old mess image format
6   * hard disks ("WIN format") in MAME harddisk format (256-byte sectors only,
7     i.e. no SCSI)
8   Files are extracted in TIFILES format.  There is a compile-time option to
9   extract text files in flat format instead, but I need to re-implement it
10   properly (using filters comes to mind).
11
12   Raphael Nabet, 2002-2004
13
14   TODO:
15   - finish and test hd support ***test sibling FDR support***
16   - check allocation bitmap against corruption when an image is opened
17*/
18
19#include <limits.h>
20#include <stdio.h>
21#include <string.h>
22#include <stdlib.h>
23#include <time.h>
24#include <assert.h>
25#include "osdepend.h"
26#include "imgtoolx.h"
27#include "harddisk.h"
28#include "imghd.h"
29
30/*
31   Concepts shared by both disk structures:
32   ----------------------------------------
33
34   In both formats, the entire disk surface is split into physical records,
35   each 256-byte-long.  For best efficiency, the sector size is usually 256
36   bytes so that one sector is equivalent to a physical record (this is true
37   with floppies and HFDC hard disks).  If the sector size is not 256 bytes
38   (e.g. 512 bytes with SCSI hard disks, possibly 128 bytes on a TI-99
39   simulator running on TI-990), sectors are grouped or split to form 256-byte
40   physical records.  Physical records are numbered from 0, with the first
41   starting on sector 0 track 0.  To avoid confusion with physical records in
42   files, such physical records will be called "absolute physical records",
43   abbreviated as "absolute physrecs" or "aphysrecs".
44
45   Disk space is allocated in units referred to as AUs.  Each AU represents an
46   integral number of 256-byte physical records.  The number of physrecs per
47   AU varies depending on the disk format and size.  AUs are numbered from 0,
48   with the first starting with absolute physrec 0.
49
50   Absolute physrec 0 contains a 256-byte record with volume information,
51   which is called "Volume Information Block", abbreviated as "vib".
52
53   To keep track of which areas on the disk are allocated and which are free,
54   disk managers maintain a bit map of allocated AUs (called "allocation
55   bitmap", abbreviated as "abm").  Each bit in the allocation bitmap
56   represents an AU: if a bit is 0, the AU is free; if a bit is 1, the AU is
57   allocated (or possibly bad if the disk manager can track bad sectors).
58   Where on the disk the abm is located depends on the disk structure (see
59   structure-specific description for details).
60
61   Files are implemented as a succession of 256-byte physical records.  To
62   avoid confusion with absolute physical records, these physical records will
63   be called "file physical records", abbreviated as "file physrecs" or
64   "fphysrecs".
65
66   Programs do normally not access file physical records directly.  They may
67   call high-level file routines that enable to create either fixed-lenght
68   logical records of any size from 1 through 255, or variable-lenght records
69   of any size from 0 through 254: logical records are grouped by file
70   managers into 256-byte physical records.  Some disk managers (HFDC and
71   SCSI) allow programs to create fixed-lenght records larger than 255 bytes,
72   too, but few programs use this possibility.  Additionally, program files
73   can be created: program files do not implement any logical record, and can
74   be seen as a flat byte stream, not unlike files under MSDOS, UNIX and the C
75   standard library.  (Unfortunately, the API for program files lacks
76   flexibility, and most programs that need to process a flat byte stream
77   will use fixed-size records of 128 bytes.)
78
79      Fixed-length records (reclen < 256) are grouped like this:
80           fphysrec 0        fphysrec 1
81         _______________   _______________
82         |R0 |R1 |R2 |X|   |R3 |R4 |R5 |X|
83         ---------------   ---------------
84                     \_/               \_/
85                    unused            unused
86               (size < reclen)   (size < reclen)
87
88      Fixed-length records (reclen > 256) are grouped like this:
89           fphysrec 0         fphysrec 1         fphysrec 2          fphysrec 3      ...
90         _________________  _________________  _________________   _________________
91         |  R0 (#0-255)  |  | R0 (#256-511) |  |R0 (#512-end)|X|   |  R1 (#0-255)  |   ...
92         -----------------  -----------------  -----------------   -----------------
93                                                             \_/
94                                                            unused
95
96      Variable lenght records are grouped like this:
97                          fphysrec 0:
98         byte:
99                 ------------------------------
100               0 |l0 = lenght of record 0 data|
101                 |----------------------------|
102               1 |                            |
103                 |                            |
104               : |       record 0 data        |
105                 |                            |
106              l0 |                            |
107                 |----------------------------|
108            l0+1 |l1 = lenght of record 1 data|
109                 |----------------------------|
110            l0+2 |                            |
111                 |                            |
112               : |       record 1 data        |
113                 |                            |
114         l0+l1+1 |                            |
115                 |----------------------------|
116               : :                            :
117               : :                            :
118                 |----------------------------|
119               n |lm = lenght of record m data|
120                 |----------------------------|
121             n+1 |                            |
122                 |                            |
123               : |       record m data        |
124                 |                            |
125            n+lm |                            |
126                 |----------------------------|
127          n+lm+1 |>ff: EOR mark               |
128                 |----------------------------|
129          n+lm+2 |                            |
130                 |                            |
131               : |           unused           |
132               : |(we should have size < lm+1)|
133                 |                            |
134             255 |                            |
135                 ------------------------------
136
137                          fphysrec 1:
138         byte:
139                 ------------------------------
140               0 |lm+1=lenght of record 0 data|
141                 |----------------------------|
142               1 |                            |
143                 |                            |
144               : |      record m+1 data       |
145                 |                            |
146            lm+1 |                            |
147                 |----------------------------|
148               : :                            :
149               : :                            :
150
151         I think the EOR mark is not required if all 256 bytes of a physical
152         record are used by logical records.
153
154
155   All files are associated with a "file descriptor record" ("fdr") that holds
156   file information (name, format, length) and points to the data AUs. The WIN
157   disk structure also supports sibling FDRs, in case a file is so fragmented
158   that all the data pointers cannot fit in one FDR; the DSK disk structure
159   does not implement any such feature, and you may be unable to append data
160   to an existing file if it is too fragmented, even though the disk is not
161   full.
162
163
164   DSK disk structure:
165   -------------------
166
167   The DSK disk structure is used for floppy disks, and a few RAMDISKs as
168   well.  It supports 1600 AUs and 16 MBytes at most (the 16 MByte value is a
169   theorical maximum, as I doubt anyone has ever created so big a DSK volume).
170
171   The disk sector size is always 256 bytes (the only potential exceptions are
172   the SCSI floppy disk units and the TI-99 simulator on TI-990, but I don't
173   know anything about either).
174
175   For some reason, the number of physrecs per AU is always a power of 2.
176   Originally, AUs always were one physical record each.  However, since the
177   allocation bitmap cannot support more than 1600 AUs, disks larger than
178   400kbytes need to have several physical records per AU.  Note that
179   relatively few disk controllers implement AUs that span multiple physical
180   records (IIRC, these are Myarc's HFDC, SCSI DSR with floppy disk interface,
181   and some upgraded Myarc and Corcomp DD floppy controllers).
182
183   The allocation bitmap is located in the VIB.  It is 200 bytes long, and
184   supports 1600 AUs at most.
185
186   Directories are implemented with a "File Descriptor Index Record" (FDIR)
187   for each directory.  The FDIR is array of 0 through 128 words, containing
188   the aphysrec address of each fdr in the directory, sorted by ascending file
189   name, terminated with a 0.  Note that, while we should be prepared to read
190   images images with 128 entries, I think (not 100% sure) that we should
191   write no more than 127 for compatibility with some existing disk managers.
192
193   Originally, the DSK structure only supported one directory level (i.e. the
194   root directory level).  The FDIR record for the root directory is always
195   located in aphysrec 1.  Moreover, Myarc extended the DSK structure to
196   support up to 3 subdirectories in the root directory (note that there is no
197   support for more subdirs, or for subdirs located in subdirs).  To do so,
198   they used an unused field of the VIB to hold the 10-char name of each
199   directory and the aphysrec address of the associated FDIR record.
200
201   aphysrec 0: Volume Information Block (VIB): see below
202   aphysrec 1: FDIR for root directory
203   Remaining AUs are used for fdr and data (and subdirectory FDIR if
204   applicable).  There is one FDIR record per directory; the FDIR points to
205   the FDR for each file in the directory.  The FDR (File Descriptor Record)
206   contains the file information (name, format, lenght, pointers to data
207   physrecs/AUs, etc).
208
209
210   WIN disk structure:
211   -------------------
212
213   The WIN disk structure is used for hard disks.  It supports 65535 AUs and
214   256 MBytes at most.
215
216   The disk sector size is 256 bytes on HFDC, 512 bytes on SCSI.  512-byte
217   sectors are split into 256-byte physical records.
218
219   We may have from 1 through 16 physrecs per AUs.  Since we cannot have more
220   than 65535 AUs, we need to have several physical records per AU in disks
221   larger than 16 Mbytes.
222
223   Contrary to the DSK disk structure, the WIN disk structure supports
224   hierarchic subdirectories, with a limit of 114 subdirectories and 127 files
225   per directory.  Each directory is associated with both a "Directory
226   Descriptor Record" (DDR) and a "File Descriptor Index Record" (FDIR).  The
227   only exception is the root directory, which uses the VIB instead of a DDR
228   (the VIB includes all the important fields of the DDR).  The DDR contains
229   some directory info (name, number of files and subdirectories directly
230   enclosed in the directory, AU address of the FDIR of the parent directory,
231   etc), the AU address of the associated FDIR, and the AU address of the DDR
232   of up to 114 subdirectories, sorted by ascending directory name.  The WIN
233   FDIR is similar to, yet different from, the DSK FDIR: it contains up to 127
234   (vs. 128) AU address (vs. aphysrec address) of each fdr in the directory,
235   sorted by ascending file name.  Additionally, it includes the AU address of
236   the associated DDR.
237
238   When a file has more than 54 data fragments, the disk manager creates
239   sibling FDRs that hold additional fragments.  (Sibling FDRs are called
240   offspring FDRs in most existing documentation, but I prefer "sibling FDRs"
241   as "offspring FDRs" wrongly suggests a directory-like hierarchy.
242   Incidentally, I cannot really figure out why they chose to duplicate the
243   FDR rather than create a file extension record, but there must be a
244   reason.)  Note that sibling FDRs usually fill unused physrecs in the AU
245   allocated for the eldest FDR, and a new AU is allocated for new sibling
246   FDRs only when the first AU is full.
247
248   aphysrec 0: Volume Information Block (VIB): see below
249   aphysrec 1-n (where n = 1+SUP(number_of_AUs/2048)): Volume bitmap
250   Remaining AUs are used for ddr, fdir, fdr and data.
251*/
252
253/* Since string length is encoded with a byte, the maximum length of a string
254is 255.  Since we need to add a device name (1 char minimum, typically 4 chars)
255and a '.' separator, we chose a practical value of 250 (though few applications
256will accept paths of such lenght). */
257#define MAX_PATH_LEN 253
258#define MAX_SAFE_PATH_LEN 250
259
260#define MAX_DIR_LEVEL 125   /* We need to put a recursion limit to avoid endless recursion hazard */
261
262
263#if 0
264#pragma mark MISCELLANEOUS UTILITIES
265#endif
266
267/*
268   Miscellaneous utilities that are used to handle TI data types
269*/
270
271typedef struct UINT16BE
272{
273   UINT8 bytes[2];
274} UINT16BE;
275
276typedef struct UINT16LE
277{
278   UINT8 bytes[2];
279} UINT16LE;
280
281INLINE UINT16 get_UINT16BE(UINT16BE word)
282{
283   return (word.bytes[0] << 8) | word.bytes[1];
284}
285
286INLINE void set_UINT16BE(UINT16BE *word, UINT16 data)
287{
288   word->bytes[0] = (data >> 8) & 0xff;
289   word->bytes[1] = data & 0xff;
290}
291
292INLINE UINT16 get_UINT16LE(UINT16LE word)
293{
294   return word.bytes[0] | (word.bytes[1] << 8);
295}
296
297INLINE void set_UINT16LE(UINT16LE *word, UINT16 data)
298{
299   word->bytes[0] = data & 0xff;
300   word->bytes[1] = (data >> 8) & 0xff;
301}
302
303/*
304   Convert a C string to a 10-character file name (padded with spaces if necessary)
305
306   dst (O): destination 10-character array
307   src (I): source C string
308*/
309static void str_to_fname(char dst[10], const char *src)
310{
311   int i;
312
313
314   i = 0;
315
316   /* copy 10 characters at most */
317   if (src)
318      while ((i<10) && (src[i]!='\0'))
319      {
320         dst[i] = src[i];
321         i++;
322      }
323
324   /* pad with spaces */
325   while (i<10)
326   {
327      dst[i] = ' ';
328      i++;
329   }
330}
331
332/*
333   Convert a 10-character file name to a C string (removing trailing spaces if necessary)
334
335   dst (O): destination C string
336   src (I): source 10-character array
337   n (I): lenght of dst buffer (string may be truncated if less than 11)
338*/
339static void fname_to_str(char *dst, const char src[10], int n)
340{
341   int i;
342   int last_nonspace;
343
344
345   /* copy 10 characters at most */
346   if (--n > 10)
347      n = 10;
348
349   /* copy filename */
350   i = 0;
351   last_nonspace = -1;
352
353   while (i<n)
354   {
355      dst[i] = src[i];
356      if (src[i] != ' ')
357         last_nonspace = i;
358      i++;
359   }
360
361   /* terminate with '\0' */
362   dst[last_nonspace+1] = '\0';
363}
364
365/*
366   Check a 10-character file name.
367
368   filename (I): 10-character array with file name
369
370   Return non-zero if the file name is invalid.
371*/
372static int check_fname(const char filename[10])
373{
374   int i;
375   int space_found_flag;
376
377
378   /* check and copy file name */
379   space_found_flag = FALSE;
380   for (i=0; i<10; i++)
381   {
382      switch (filename[i])
383      {
384      case '.':
385      case '\0':
386         /* illegal characters */
387         return 1;
388      case ' ':
389         /* illegal in a file name, but file names shorter than 10
390         characters are padded with spaces */
391         space_found_flag = TRUE;
392         break;
393      default:
394         /* all other characters are legal (though non-ASCII characters,
395         control characters and even lower-case characters are not
396         recommended) */
397         if (space_found_flag)
398            return 1;
399         break;
400      }
401   }
402
403   return 0;
404}
405
406/*
407   Check a file path.
408
409   fpath (I): C string with file path
410
411   Return non-zero if the file path is invalid.
412*/
413static int check_fpath(const char *fpath)
414{
415   const char *element_start, *element_end;
416   int element_len;
417
418
419   /* first check that the path is not too long and that there is no space
420   character */
421   if ((strlen(fpath) > MAX_PATH_LEN) || strchr(fpath, ' '))
422      return 1;
423
424   /* check that each path element has an acceptable lenght */
425   element_start = fpath;
426   do
427   {
428      /* find next path element */
429      element_end = strchr(element_start, '.');
430      element_len = element_end ? (element_end - element_start) : strlen(element_start);
431      if ((element_len > 10) || (element_len == 0))
432         return 1;
433
434      /* iterate */
435      if (element_end)
436         element_start = element_end+1;
437      else
438         element_start = NULL;
439   }
440   while (element_start);
441
442   return 0;
443}
444
445#if 0
446#pragma mark -
447#pragma mark LEVEL 1 DISK ROUTINES
448#endif
449
450/*
451   Level 1 deals with accessing the disk hardware (in our case, the raw disk
452   image).
453
454   Higher level routines will only know the disk as a succession of
455   256-byte-long physical records addressed by a linear address.
456*/
457
458/*
459   Disk geometry
460*/
461typedef struct ti99_geometry
462{
463   int secspertrack;
464   int cylinders;
465   int heads;
466} ti99_geometry;
467
468/*
469   Physical sector address
470*/
471typedef struct ti99_sector_address
472{
473   int sector;
474   int cylinder;
475   int side;
476} ti99_sector_address;
477
478/*
479   Time stamp (used in fdr, and WIN VIB/DDR)
480*/
481typedef struct ti99_date_time
482{
483   UINT8 time_MSB, time_LSB;/* 0-4: hour, 5-10: minutes, 11-15: seconds/2 */
484   UINT8 date_MSB, date_LSB;/* 0-6: year, 7-10: month, 11-15: day */
485} ti99_date_time;
486
487/*
488   Subdirectory descriptor (HFDC only)
489
490   The HFDC supports up to 3 subdirectories.
491*/
492typedef struct dsk_subdir
493{
494   char name[10];         /* subdirectory name (10 characters, pad with spaces) */
495   UINT16BE fdir_aphysrec;   /* aphysrec address of fdir record for this subdirectory */
496} dsk_subdir;
497
498/*
499   DSK VIB record
500
501   Most fields in this record are only revelant to level 2 routines, but level
502   1 routines need the disk geometry information extracted from the VIB.
503*/
504typedef struct dsk_vib
505{
506   char name[10];         /* disk volume name (10 characters, pad with spaces) */
507   UINT16BE totphysrecs;   /* total number of physrecs on disk (usually 360, */
508                        /* 720, 640, 1280 or 1440).  (TI originally */
509                        /* said it should be the total number of AUs, */
510                        /* but, in practice, DSRs that supports disks */
511                        /* over 400kbytes (e.g. HFDC) write the total */
512                        /* number of physrecs.) */
513   UINT8 secspertrack;      /* sectors per track (usually 9 (FM SD), */
514                        /* 16 or 18 (MFM DD), or 36 (MFM HD) */
515   UINT8 id[3];         /* 'DSK' */
516   UINT8 protection;      /* 'P' if disk is protected, ' ' otherwise. */
517   UINT8 cylinders;      /* tracks per side (usually 40) */
518   UINT8 heads;         /* sides (1 or 2) */
519   UINT8 density;         /* density: 1 (FM SD), 2 (MFM DD), or 3 (MFM HD) */
520   dsk_subdir subdir[3];   /* descriptor for up to 3 subdirectories (HFDC only) */
521                        /* reserved by TI */
522   UINT8 abm[200];         /* allocation bitmap: there is one bit per AU. */
523                        /* A binary 1 in a bit position indicates that */
524                        /* the allocation unit associated with that */
525                        /* bit has been allocated. */
526                        /* Bits corresponding to system reserved AUs, */
527                        /* non-existant AUs, and bad AUs, are set to one, too. */
528                        /* (AU 0 is associated to LSBit of byte 0, */
529                        /* AU 7 to MSBit of byte 0, AU 8 to LSBit */
530                        /* of byte 1, etc.) */
531} dsk_vib;
532
533typedef enum
534{
535   if_mess,
536   if_v9t9,
537   if_pc99_fm,
538   if_pc99_mfm,
539   if_harddisk
540} ti99_img_format;
541
542/*
543   level-1 disk image descriptor
544*/
545typedef struct ti99_lvl1_imgref
546{
547   ti99_img_format img_format;   /* tells the image format */
548   imgtool_stream *file_handle;      /* imgtool file handle */
549   struct mess_hard_disk_file harddisk_handle;      /* MAME harddisk handle (harddisk format) */
550   ti99_geometry geometry;      /* geometry */
551   unsigned pc99_track_len;      /* unformatted track lenght (pc99 format) */
552   UINT32 *pc99_data_offset_array;   /* offset for each sector (pc99 format) */
553} ti99_lvl1_imgref;
554
555/*
556   calculate CRC for data address marks or sector data
557
558   crc (I/O): current CRC value to be updated (initialize to 0xffff before
559      calling this function for the first time)
560   value: new byte of data to update the CRC with
561*/
562static void calc_crc(UINT16 *crc, UINT8 value)
563{
564   UINT8 l, h;
565
566   l = value ^ (*crc >> 8);
567   *crc = (*crc & 0xff) | (l << 8);
568   l >>= 4;
569   l ^= (*crc >> 8);
570   *crc <<= 8;
571   *crc = (*crc & 0xff00) | l;
572   l = (l << 4) | (l >> 4);
573   h = l;
574   l = (l << 2) | (l >> 6);
575   l &= 0x1f;
576   *crc = *crc ^ (l << 8);
577   l = h & 0xf0;
578   *crc = *crc ^ (l << 8);
579   l = (h << 1) | (h >> 7);
580   l &= 0xe0;
581   *crc = *crc ^ l;
582}
583
584/*
585   Parse a PC99 disk image
586
587   file_handle (I/O): imgtool file handle
588   fm_format (I): if true, the image is in FM format, otherwise it is in MFM
589      format
590   pass (I): 0 for first pass, 1 for second pass
591   vib (O): buffer where the vib should be stored (first pass)
592   geometry (O): disk image geometry (second pass)
593   data_offset_array (O): array of data offset to generate (second pass)
594   out_track_len (O): track lenght is returned there
595
596   Return imgtool error code
597*/
598#define MAX_TRACK_LEN 6872
599#define DATA_OFFSET_NONE 0xffffffff
600static int parse_pc99_image(imgtool_stream *file_handle, int fm_format, int pass, dsk_vib *vib, const ti99_geometry *geometry, UINT32 *data_offset_array, unsigned *out_track_len)
601{
602   int track_len, num_tracks;   /* lenght of a track in bytes, and number of tracks */
603   int phys_track;
604   int expected_cylinder, expected_head;
605   int track_start_pos, track_pos;
606   UINT8 c;
607   UINT8 cylinder, head, sector;
608   int seclen;
609   UINT8 crc1, crc2;
610   UINT16 crc;
611   long data_offset;
612   UINT8 track_buf[MAX_TRACK_LEN];
613   int i;
614
615   if (fm_format)
616      track_len = 3253;
617   else
618      track_len = 6872;
619
620   if (out_track_len)
621      *out_track_len = track_len;
622
623   if (stream_size(file_handle) % track_len)
624      return IMGTOOLERR_CORRUPTIMAGE;
625
626   num_tracks = stream_size(file_handle) / track_len;
627   if (num_tracks <= 0)
628      return IMGTOOLERR_CORRUPTIMAGE;
629
630   /* we only support 40-track-per-side images */
631   if ((num_tracks != 40) && (num_tracks != 80))
632      return IMGTOOLERR_UNIMPLEMENTED;
633
634   if (pass == 1)
635   {
636      /* initialize offset map */
637      for (head = 0; head < geometry->heads; head++)
638         for (cylinder = 0; cylinder < geometry->cylinders; cylinder++)
639            for (sector = 0; sector < geometry->secspertrack; sector++)
640               data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] = DATA_OFFSET_NONE;
641   }
642   /* rewind to start of file */
643   stream_seek(file_handle, 0, SEEK_SET);
644
645   /* pass 0 only looks for vib in track 0; pass 1 scans every track */
646   for (phys_track=0; phys_track < ((pass == 1) ? num_tracks : 1); phys_track++)
647   {
648      if (stream_read(file_handle, track_buf, track_len) != track_len)
649         return IMGTOOLERR_READERROR;
650
651      /* we only support 40-track-per-side images */
652      expected_cylinder = phys_track % 40;
653      expected_head = phys_track / 40;
654
655      track_start_pos = 0;
656
657      while (track_start_pos < track_len)
658      {
659         if (fm_format)
660         {
661            do
662            {
663               c = track_buf[track_start_pos];
664               track_start_pos++;
665            } while ((c != 0xfe) && (track_start_pos < track_len));
666
667            if (c != 0xfe)
668               break;
669
670            track_pos = track_start_pos;
671
672            crc = 0xffff;
673            calc_crc(& crc, c);
674         }
675         else
676         {
677            do
678            {
679               c = track_buf[track_start_pos];
680               track_start_pos++;
681            } while ((c != 0xa1) && (track_start_pos < track_len));
682
683            if (c != 0xa1)
684               break;
685
686            track_pos = track_start_pos;
687
688            c = track_buf[track_pos];
689            track_pos++;
690            if (track_pos == track_len)
691               track_pos = 0;
692
693            if (c != 0xa1)
694               continue;
695
696            c = track_buf[track_pos];
697            track_pos++;
698            if (track_pos == track_len)
699               track_pos = 0;
700
701            if (c != 0xa1)
702               continue;
703
704            crc = 0xffff;
705            calc_crc(& crc, c);
706
707            c = track_buf[track_pos];
708            track_pos++;
709            if (track_pos == track_len)
710               track_pos = 0;
711
712            if (c != 0xfe)
713               continue;
714         }
715
716         c = track_buf[track_pos];
717         track_pos++;
718         if (track_pos == track_len)
719            track_pos = 0;
720
721         cylinder = c;
722         calc_crc(& crc, c);
723
724         c = track_buf[track_pos];
725         track_pos++;
726         if (track_pos == track_len)
727            track_pos = 0;
728
729         head = c;
730         calc_crc(& crc, c);
731
732         c = track_buf[track_pos];
733         track_pos++;
734         if (track_pos == track_len)
735            track_pos = 0;
736
737         sector = c;
738         calc_crc(& crc, c);
739
740         c = track_buf[track_pos];
741         track_pos++;
742         if (track_pos == track_len)
743            track_pos = 0;
744
745         seclen = 128 << c;
746         calc_crc(& crc, c);
747
748         c = track_buf[track_pos];
749         track_pos++;
750         if (track_pos == track_len)
751            track_pos = 0;
752
753         crc1 = c;
754         calc_crc(& crc, c);
755
756         c = track_buf[track_pos];
757         track_pos++;
758         if (track_pos == track_len)
759            track_pos = 0;
760
761         crc2 = c;
762         calc_crc(& crc, c);
763
764         /* CRC seems to be completely hosed */
765         /*if (crc)
766            printf("aargh!");*/
767         if ((seclen != 256) || (crc1 != 0xf7) || (crc2 != 0xf7)
768               || (cylinder != expected_cylinder) || (head != expected_head)
769               || ((pass == 1) && ((cylinder >= geometry->cylinders)
770                              || (head >= geometry->heads)
771                              || (sector >= geometry->secspertrack))))
772            continue;
773
774         c = track_buf[track_pos];
775         track_pos++;
776         if (track_pos == track_len)
777            track_pos = 0;
778
779         while (c == (fm_format ? 0xff : 0x4e))
780         {
781            c = track_buf[track_pos];
782            track_pos++;
783            if (track_pos == track_len)
784               track_pos = 0;
785         }
786
787         while (c == 0x00)
788         {
789            c = track_buf[track_pos];
790            track_pos++;
791            if (track_pos == track_len)
792               track_pos = 0;
793         }
794
795         if (fm_format)
796         {
797            if (c != 0xfb)
798               continue;
799
800            crc = 0xffff;
801            calc_crc(& crc, c);
802         }
803         else
804         {
805            if (c != 0xa1)
806               continue;
807
808            c = track_buf[track_pos];
809            track_pos++;
810            if (track_pos == track_len)
811               track_pos = 0;
812
813            if (c != 0xa1)
814               continue;
815
816            c = track_buf[track_pos];
817            track_pos++;
818            if (track_pos == track_len)
819               track_pos = 0;
820
821            if (c != 0xa1)
822               continue;
823
824            crc = 0xffff;
825            calc_crc(& crc, c);
826
827            c = track_buf[track_pos];
828            track_pos++;
829            if (track_pos == track_len)
830               track_pos = 0;
831
832            if (c != 0xfb)
833               continue;
834         }
835         data_offset = track_pos;
836         for (i=0; i<seclen; i++)
837         {
838            c = track_buf[track_pos];
839            track_pos++;
840            if (track_pos == track_len)
841               track_pos = 0;
842
843            calc_crc(& crc, c);
844         }
845
846         c = track_buf[track_pos];
847         track_pos++;
848         if (track_pos == track_len)
849            track_pos = 0;
850
851         crc1 = c;
852         calc_crc(& crc, c);
853
854         c = track_buf[track_pos];
855         track_pos++;
856         if (track_pos == track_len)
857            track_pos = 0;
858
859         crc2 = c;
860         calc_crc(& crc, c);
861
862         /* CRC seems to be completely hosed */
863         /*if (crc)
864            printf("aargh!");*/
865         if ((crc1 != 0xf7) || (crc2 != 0xf7))
866            continue;
867
868         switch (pass)
869         {
870         case 0:
871            if ((cylinder == 0) && (head == 0) && (sector == 0))
872            {
873               /* return vib */
874               if ((data_offset + 256) <= track_len)
875                  memcpy(vib, track_buf + data_offset, 256);
876               else
877               {
878                  memcpy((UINT8 *)vib, track_buf + data_offset, track_len-data_offset);
879                  memcpy((UINT8 *)vib + (track_len-data_offset), track_buf, 256-(track_len-data_offset));
880               }
881               return 0;
882            }
883            break;
884
885         case 1:
886            /* set up offset map */
887            if (data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] != DATA_OFFSET_NONE)
888               /* error: duplicate sector */
889               return IMGTOOLERR_CORRUPTIMAGE;
890            data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] = data_offset;
891            break;
892         }
893      }
894   }
895
896   if (pass == 0)
897      return IMGTOOLERR_CORRUPTIMAGE;
898
899   if (pass == 1)
900   {
901      /* check offset map */
902      for (head = 0; head < geometry->heads; head++)
903         for (cylinder = 0; cylinder < geometry->cylinders; cylinder++)
904            for (sector = 0; sector < geometry->secspertrack; sector++)
905               if (data_offset_array[(head*geometry->cylinders + cylinder)*geometry->secspertrack + sector] == DATA_OFFSET_NONE)
906                  /* error: missing sector */
907                  return IMGTOOLERR_CORRUPTIMAGE;
908   }
909
910   return 0;
911}
912
913
914/*
915   Read the volume information block (aphysrec 0) assuming no geometry
916   information.  (Called when an image is opened to figure out the
917   geometry information.)
918
919   file_handle (I/O): imgtool file handle
920   img_format (I): image format (MESS, V9T9 or PC99)
921   dest (O): pointer to 256-byte destination buffer
922
923   Return imgtool error code
924*/
925static int read_image_vib_no_geometry(imgtool_stream *file_handle, ti99_img_format img_format, dsk_vib *dest)
926{
927   int reply;
928
929   switch (img_format)
930   {
931   case if_mess:
932   case if_v9t9:
933      /* seek to sector */
934      reply = stream_seek(file_handle, 0, SEEK_SET);
935      if (reply)
936         return IMGTOOLERR_READERROR;
937      /* read it */
938      reply = stream_read(file_handle, dest, 256);
939      if (reply != 256)
940         return IMGTOOLERR_READERROR;
941      return 0;
942
943   case if_pc99_fm:
944   case if_pc99_mfm:
945      return parse_pc99_image(file_handle, img_format == if_pc99_fm, 0, dest, NULL, NULL, NULL);
946
947   case if_harddisk:
948      /* not implemented, because we don't need it */
949      break;
950   }
951
952   return IMGTOOLERR_UNIMPLEMENTED;
953}
954
955/*
956   Open a disk image at level 1
957
958   file_handle (I/O): imgtool file handle
959   img_format (I): image format (MESS, V9T9, PC99, or MAME harddisk)
960   l1_img (O): level-1 image handle
961   vib (O): buffer where the vib should be stored (floppy images only)
962
963   Return imgtool error code
964*/
965static imgtoolerr_t open_image_lvl1(imgtool_stream *file_handle, ti99_img_format img_format, ti99_lvl1_imgref *l1_img, dsk_vib *vib)
966{
967   imgtoolerr_t err;
968   int reply;
969   int totphysrecs;
970
971
972   l1_img->img_format = img_format;
973   l1_img->file_handle = file_handle;
974
975   if (img_format == if_harddisk)
976   {
977      const hard_disk_info *info;
978
979      err = imghd_open(file_handle, &l1_img->harddisk_handle);
980      if (err)
981         return err;
982
983      info = imghd_get_header(&l1_img->harddisk_handle);
984      l1_img->geometry.cylinders = info->cylinders;
985      l1_img->geometry.heads = info->heads;
986      l1_img->geometry.secspertrack = info->sectors;
987      if (info->sectorbytes != 256)
988      {
989         imghd_close(&l1_img->harddisk_handle);
990         return IMGTOOLERR_CORRUPTIMAGE;   /* TODO: support 512-byte sectors */
991      }
992
993      /* read vib */
994      /*reply = read_absolute_physrec(l1_img, 0, vib);
995      if (reply)
996         return reply;*/
997   }
998   else
999   {
1000      /* read vib */
1001      reply = read_image_vib_no_geometry(file_handle, img_format, vib);
1002      if (reply)
1003         return reply;
1004
1005      /* extract geometry information */
1006      totphysrecs = get_UINT16BE(vib->totphysrecs);
1007
1008      l1_img->geometry.secspertrack = vib->secspertrack;
1009      if (l1_img->geometry.secspertrack == 0)
1010         /* Some images might be like this, because the original SSSD TI
1011         controller always assumes 9. */
1012         l1_img->geometry.secspertrack = 9;
1013      l1_img->geometry.cylinders = vib->cylinders;
1014      if (l1_img->geometry.cylinders == 0)
1015         /* Some images are like this, because the original SSSD TI
1016         controller always assumes 40. */
1017         l1_img->geometry.cylinders = 40;
1018      l1_img->geometry.heads = vib->heads;
1019      if (l1_img->geometry.heads == 0)
1020         /* Some images are like this, because the original SSSD TI
1021         controller always assumes that tracks beyond 40 are on side 2. */
1022         l1_img->geometry.heads = totphysrecs / (l1_img->geometry.secspertrack * l1_img->geometry.cylinders);
1023
1024      /* check information */
1025      if ((totphysrecs != (l1_img->geometry.secspertrack * l1_img->geometry.cylinders * l1_img->geometry.heads))
1026            || (totphysrecs < 2)
1027            || memcmp(vib->id, "DSK", 3) || (! strchr(" P", vib->id[3]))
1028            || (((img_format == if_mess) || (img_format == if_v9t9))
1029               && (stream_size(file_handle) != totphysrecs*256)))
1030         return IMGTOOLERR_CORRUPTIMAGE;
1031
1032      if ((img_format == if_pc99_fm) || (img_format == if_pc99_mfm))
1033      {
1034         l1_img->pc99_data_offset_array = malloc(sizeof(*l1_img->pc99_data_offset_array)*totphysrecs);
1035         if (! l1_img->pc99_data_offset_array)
1036            return IMGTOOLERR_OUTOFMEMORY;
1037         reply = parse_pc99_image(file_handle, img_format == if_pc99_fm, 1, NULL, & l1_img->geometry, l1_img->pc99_data_offset_array, &l1_img->pc99_track_len);
1038         if (reply)
1039         {
1040            free(l1_img->pc99_data_offset_array);
1041            return reply;
1042         }
1043      }
1044   }
1045
1046   return 0;
1047}
1048
1049/*
1050   Close a disk image at level 1
1051
1052   l1_img (I/O): level-1 image handle
1053
1054   Return imgtool error code
1055*/
1056static void close_image_lvl1(ti99_lvl1_imgref *l1_img)
1057{
1058   if (l1_img->img_format == if_harddisk)
1059   {
1060      imghd_close(&l1_img->harddisk_handle);
1061   }
1062
1063   stream_close(l1_img->file_handle);
1064
1065   if ((l1_img->img_format == if_pc99_fm) || (l1_img->img_format == if_pc99_mfm))
1066      free(l1_img->pc99_data_offset_array);
1067}
1068
1069/*
1070   Convert physical sector address to offset in disk image (old MESS and V9T9
1071   formats only)
1072
1073   l1_img (I/O): level-1 image handle
1074   address (I): physical sector address
1075
1076   Return offset in image
1077*/
1078INLINE int sector_address_to_image_offset(const ti99_lvl1_imgref *l1_img, const ti99_sector_address *address)
1079{
1080   int offset = 0;
1081
1082   switch (l1_img->img_format)
1083   {
1084   case if_mess:
1085      /* old MESS format */
1086      offset = (((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector)*256;
1087      break;
1088
1089   case if_v9t9:
1090      /* V9T9 format */
1091      if (address->side & 1)
1092         /* on side 1, tracks are stored in the reverse order */
1093         offset = (((address->side*l1_img->geometry.cylinders) + (l1_img->geometry.cylinders-1 - address->cylinder))*l1_img->geometry.secspertrack + address->sector)*256;
1094      else
1095         offset = (((address->side*l1_img->geometry.cylinders) + address->cylinder)*l1_img->geometry.secspertrack + address->sector)*256;
1096      break;
1097
1098   case if_pc99_fm:
1099   case if_pc99_mfm:
1100      /* pc99 format */
1101   case if_harddisk:
1102      /* harddisk format */
1103      assert(1);      /* not implemented */
1104      break;
1105   }
1106
1107   return offset;
1108}
1109
1110/*
1111   Read one 256-byte sector from a disk image
1112
1113   l1_img (I/O): level-1 image handle
1114   address (I): physical sector address
1115   dest (O): pointer to 256-byte destination buffer
1116
1117   Return non-zero on error
1118*/
1119static int read_sector(ti99_lvl1_imgref *l1_img, const ti99_sector_address *address, void *dest)
1120{
1121   int reply;
1122   UINT32 track_len, track_offset, sector_offset;
1123
1124   switch (l1_img->img_format)
1125   {
1126   case if_mess:
1127      /* old MESS format */
1128   case if_v9t9:
1129      /* V9T9 format */
1130      /* seek to sector */
1131      reply = stream_seek(l1_img->file_handle, sector_address_to_image_offset(l1_img, address), SEEK_SET);
1132      if (reply)
1133         return 1;
1134      /* read it */
1135      reply = stream_read(l1_img->file_handle, dest, 256);
1136      if (reply != 256)
1137         return 1;
1138      break;
1139
1140   case if_pc99_fm:
1141   case if_pc99_mfm:
1142      /* pc99 format */
1143      track_len = l1_img->pc99_track_len;
1144      track_offset = (address->side*l1_img->geometry.cylinders + address->cylinder)*track_len;
1145      sector_offset = l1_img->pc99_data_offset_array[(address->side*l1_img->geometry.cylinders + address->cylinder)*l1_img->geometry.secspertrack + address->sector];
1146
1147      if ((sector_offset + 256) <= track_len)
1148      {
1149         /* seek to sector */
1150         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1151         if (reply)
1152            return 1;
1153         /* read it */
1154         reply = stream_read(l1_img->file_handle, dest, 256);
1155         if (reply != 256)
1156            return 1;
1157      }
1158      else
1159      {
1160         /* seek to sector */
1161         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1162         if (reply)
1163            return 1;
1164         /* read first chunk (until end of track) */
1165         reply = stream_read(l1_img->file_handle, (UINT8 *)dest, track_len-sector_offset);
1166         if (reply != track_len-sector_offset)
1167            return 1;
1168
1169         /* wrap to start of track */
1170         reply = stream_seek(l1_img->file_handle, track_offset, SEEK_SET);
1171         if (reply)
1172            return 1;
1173         /* read remnant of sector */
1174         reply = stream_read(l1_img->file_handle, (UINT8 *)dest + (track_len-sector_offset), 256-(track_len-sector_offset));
1175         if (reply != 256-(track_len-sector_offset))
1176            return 1;
1177      }
1178      break;
1179
1180   case if_harddisk:
1181      /* not implemented */
1182      assert(1);
1183      /*return imghd_read(l1_img->harddisk_handle, ((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector, 1, dest) != 1;*/
1184      break;
1185   }
1186
1187   return 0;
1188}
1189
1190/*
1191   Write one 256-byte sector to a disk image
1192
1193   l1_img (I/O): level-1 image handle
1194   address (I): physical sector address
1195   src (I): pointer to 256-byte source buffer
1196
1197   Return non-zero on error
1198*/
1199static int write_sector(ti99_lvl1_imgref *l1_img, const ti99_sector_address *address, const void *src)
1200{
1201   int reply;
1202   UINT32 track_len, track_offset, sector_offset;
1203
1204   switch (l1_img->img_format)
1205   {
1206   case if_mess:
1207      /* old MESS format */
1208   case if_v9t9:
1209      /* V9T9 format */
1210      /* seek to sector */
1211      reply = stream_seek(l1_img->file_handle, sector_address_to_image_offset(l1_img, address), SEEK_SET);
1212      if (reply)
1213         return 1;
1214      /* write it */
1215      reply = stream_write(l1_img->file_handle, src, 256);
1216      if (reply != 256)
1217         return 1;
1218      break;
1219
1220   case if_pc99_fm:
1221   case if_pc99_mfm:
1222      /* pc99 format */
1223      track_len = l1_img->pc99_track_len;
1224      track_offset = (address->side*l1_img->geometry.cylinders + address->cylinder)*track_len;
1225      sector_offset = l1_img->pc99_data_offset_array[(address->side*l1_img->geometry.cylinders + address->cylinder)*l1_img->geometry.secspertrack + address->sector];
1226
1227      if ((sector_offset + 256) <= track_len)
1228      {
1229         /* seek to sector */
1230         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1231         if (reply)
1232            return 1;
1233         /* write it */
1234         reply = stream_write(l1_img->file_handle, src, 256);
1235         if (reply != 256)
1236            return 1;
1237      }
1238      else
1239      {
1240         /* seek to sector */
1241         reply = stream_seek(l1_img->file_handle, track_offset+sector_offset, SEEK_SET);
1242         if (reply)
1243            return 1;
1244         /* write first chunk (until end of track) */
1245         reply = stream_write(l1_img->file_handle, (UINT8 *)src, track_len-sector_offset);
1246         if (reply != track_len-sector_offset)
1247            return 1;
1248
1249         /* wrap to start of track */
1250         reply = stream_seek(l1_img->file_handle, track_offset, SEEK_SET);
1251         if (reply)
1252            return 1;
1253         /* write remnant of sector */
1254         reply = stream_write(l1_img->file_handle, (UINT8 *)src + (track_len-sector_offset), 256-(track_len-sector_offset));
1255         if (reply != 256-(track_len-sector_offset))
1256            return 1;
1257      }
1258      break;
1259
1260   case if_harddisk:
1261      /* not implemented */
1262      assert(1);
1263      /*return imghd_write(l1_img->harddisk_handle, ((address->cylinder*l1_img->geometry.heads) + address->side)*l1_img->geometry.secspertrack + address->sector, 1, src) != 1;*/
1264      break;
1265   }
1266
1267   return 0;
1268}
1269
1270/*
1271   Convert physical record address to sector address (DSK format)
1272
1273   aphysrec (I): absolute physrec address
1274   geometry (I): disk image geometry
1275   address (O): physical sector address
1276*/
1277static void dsk_aphysrec_to_sector_address(int aphysrec, const ti99_geometry *geometry, ti99_sector_address *address)
1278{
1279   address->sector = aphysrec % geometry->secspertrack;
1280   aphysrec /= geometry->secspertrack;
1281   address->cylinder = aphysrec % geometry->cylinders;
1282   address->side = aphysrec / geometry->cylinders;
1283   if (address->side & 1)
1284      /* on side 1, tracks are stored in the reverse order */
1285      address->cylinder = geometry->cylinders-1 - address->cylinder;
1286}
1287
1288/*
1289   Convert physical record address to sector address (WIN format for HFDC)
1290
1291   Note that physical address translation makes sense for HFDC, but not SCSI.
1292
1293   aphysrec (I): absolute physrec address
1294   geometry (I): disk image geometry
1295   address (O): physical sector address
1296*/
1297/*static void win_aphysrec_to_sector_address(int aphysrec, const ti99_geometry *geometry, ti99_sector_address *address)
1298{
1299   address.sector = aphysrec % l1_img->geometry.secspertrack;
1300   aphysrec /= l1_img->geometry.secspertrack;
1301   address.side = aphysrec % l1_img->geometry.heads;
1302   address.cylinder = aphysrec / l1_img->geometry.heads;
1303}*/
1304
1305/*
1306   Read one 256-byte physical record from a disk image
1307
1308   l1_img (I/O): level-1 image handle
1309   aphysrec (I): absolute physrec address
1310   dest (O): pointer to 256-byte destination buffer
1311
1312   Return non-zero on error
1313*/
1314static int read_absolute_physrec(ti99_lvl1_imgref *l1_img, unsigned aphysrec, void *dest)
1315{
1316   ti99_sector_address address;
1317
1318
1319   if (l1_img->img_format == if_harddisk)
1320   {
1321      /*win_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1322
1323      return read_sector(l1_img, & address, dest);*/
1324
1325      return imghd_read(&l1_img->harddisk_handle, aphysrec, dest) != IMGTOOLERR_SUCCESS;
1326   }
1327   else
1328   {
1329      dsk_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1330
1331      return read_sector(l1_img, & address, dest);
1332   }
1333}
1334
1335/*
1336   Write one 256-byte physical record to a disk image
1337
1338   l1_img (I/O): level-1 image handle
1339   aphysrec (I): absolute physrec address
1340   src (I): pointer to 256-byte source buffer
1341
1342   Return non-zero on error
1343*/
1344static int write_absolute_physrec(ti99_lvl1_imgref *l1_img, unsigned aphysrec, const void *src)
1345{
1346   ti99_sector_address address;
1347
1348
1349   if (l1_img->img_format == if_harddisk)
1350   {
1351      /*win_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1352
1353      return write_sector(l1_img, & address, dest);*/
1354
1355      return imghd_write(&l1_img->harddisk_handle, aphysrec, src) != IMGTOOLERR_SUCCESS;
1356   }
1357   else
1358   {
1359      dsk_aphysrec_to_sector_address(aphysrec, & l1_img->geometry, & address);
1360
1361      return write_sector(l1_img, & address, src);
1362   }
1363}
1364
1365#if 0
1366#pragma mark -
1367#pragma mark LEVEL 2 DISK ROUTINES
1368#endif
1369
1370/*
1371   Level 2 implements files as a succession of 256-byte-long physical records.
1372
1373   Level 2 implements allocation bitmap (and AU), disk catalog, etc.
1374*/
1375
1376/*
1377   WIN VIB/DDR record
1378*/
1379typedef struct win_vib_ddr
1380{
1381   char name[10];         /* disk volume name (10 characters, pad with spaces) */
1382   UINT16BE totAUs;      /* total number of AUs */
1383   UINT8 secspertrack;      /* HFDC: sectors per track (typically 32) */
1384                     /* SCSI: reserved */
1385   union
1386   {
1387      struct
1388      {
1389         UINT8 id[3];   /* V1 VIB: 'WIN' */
1390      } vib_v1;
1391
1392      struct            /* V2 VIB: extra params */
1393      {
1394         UINT8 res_AUs;   /* # AUs reserved for vib, bitmap, ddr, fdir and fdr, divided by 64 */
1395         UINT8 step_spd;   /* HFDC: step speed (0-7) */
1396                     /* SCSI: reserved */
1397         UINT8 red_w_cur;/* HFDC: reduced write current cylinder, divided by 8 */
1398                     /* SCSI: reserved */
1399      } vib_v2;
1400
1401      struct
1402      {
1403         UINT8 id[3];   /* DDR: 'DIR' */
1404      } ddr;
1405   } u;
1406   UINT16BE params;      /* bits 0-3: sectors/AU - 1 */
1407                     /* HFDC: */
1408                        /* bits 4-7: # heads - 1 */
1409                        /* bit 8: V1: buffered head stepping flag */
1410                        /*        V2: reserved */
1411                        /* bit 9-15: write precompensation track, divided by 16 */
1412                     /* SCSI: */
1413                        /* bits 4-15: reserved */
1414   ti99_date_time creation;/* date and time of creation */
1415   UINT8 num_files;      /* number of files in directory */
1416   UINT8 num_subdirs;      /* number of subdirectories in directory */
1417   UINT16BE fdir_AU;      /* points to root directory fdir */
1418   union
1419   {
1420      struct
1421      {
1422         UINT16BE dsk1_AU;   /* HFDC: points to current dsk1 emulation image (0 if none) */
1423                        /* SCSI: reserved */
1424      } vib;
1425
1426      struct
1427      {
1428         UINT16BE parent_ddr_AU;   /* points to parent directory DDR */
1429      } ddr;
1430   } u2;
1431   UINT16BE subdir_AU[114];/* points to all subdirectory DDRs */
1432} win_vib_ddr;
1433
1434/*
1435   AU format
1436*/
1437typedef struct ti99_AUformat
1438{
1439   int totAUs;            /* total number of AUs */
1440   int physrecsperAU;      /* number of 256-byte physical records per AU */
1441} ti99_AUformat;
1442
1443/*
1444   DSK directory reference: 0 for root, 1 for 1st subdir, 2 for 2nd subdir, 3
1445   for 3rd subdir
1446*/
1447/*typedef int dir_ref;*/
1448
1449/*
1450   catalog entry (used for in-memory catalog)
1451*/
1452typedef struct dir_entry
1453{
1454   UINT16 dir_ptr;         /* DSK: unused */
1455                     /* WIN: AU address of the DDR for this directory */
1456   char name[10];         /* name of this directory (copied from the VIB for DSK, DDR for WIN) */
1457} dir_entry;
1458
1459typedef struct file_entry
1460{
1461   UINT16 fdr_ptr;         /* DSK: aphysrec address of the FDR for this file */
1462                     /* WIN: AU address of the FDR for this file */
1463   char name[10];         /* name of this file (copied from FDR) */
1464} file_entry;
1465
1466typedef struct ti99_catalog
1467{
1468   int num_subdirs;      /* number of subdirectories */
1469   int num_files;         /* number of files */
1470   dir_entry subdirs[114];   /* description of each subdir */
1471   file_entry files[128];   /* description of each file */
1472} ti99_catalog;
1473
1474/*
1475   level-2 disk image descriptor
1476*/
1477typedef struct ti99_lvl2_imgref_dsk
1478{
1479   UINT16 totphysrecs;            /* total number of aphysrecs (extracted from vib record in aphysrec 0) */
1480   ti99_catalog catalogs[4];      /* catalog of root directory and up to 3 subdirectories */
1481   UINT16 fdir_aphysrec[4];      /* fdir aphysrec address for root directory
1482                              and up to 3 subdirectories */
1483} ti99_lvl2_imgref_dsk;
1484
1485typedef struct ti99_lvl2_imgref_win
1486{
1487   enum
1488   {
1489      win_vib_v1,
1490      win_vib_v2
1491   } vib_version;         /* version of the vib record in aphysrec 0 (see win_vib_ddr) */
1492} ti99_lvl2_imgref_win;
1493
1494typedef struct ti99_lvl2_imgref
1495{
1496   ti99_lvl1_imgref l1_img;/* image format, imgtool image handle, image geometry */
1497   ti99_AUformat AUformat;   /* AU format */
1498   int data_offset;      /* In order to reduce seek times when searching the
1499                        disk for a given file name, fdr (and ddr, and
1500                        fdir) records are preferentially allocated in
1501                        AUs n to data_offset, whereas data records are
1502                        preferentially allocated in AUs starting at
1503                        data_offset. */
1504                     /* With the DSK disk structure, n is always 2 (if 1
1505                        physrec per AU) or 1 (if 2 physrecs per AU or
1506                        more), and data_offset is arbitrarily chosen as
1507                        34. */
1508                     /* With the WIN disk structure, n depends on the
1509                        size of the volume bitmap, which itself depends
1510                        on the number of AUs on disk (we always have n
1511                        <= 33), and data_offset is read from the vib
1512                        record (except with the obsolete v1 VIB, where
1513                        we use a default value of 64). */
1514   char vol_name[10];      /* cached volume name (extracted from vib record in aphysrec 0) */
1515
1516   UINT8 abm[8192];      /* allocation bitmap */
1517
1518   enum
1519   {
1520      L2I_DSK,
1521      L2I_WIN
1522   } type;               /* structure format */
1523
1524   union
1525   {
1526      ti99_lvl2_imgref_dsk dsk;
1527      ti99_lvl2_imgref_win win;
1528   } u;               /* structure-specific info */
1529} ti99_lvl2_imgref;
1530
1531/*
1532   file flags found in fdr (and tifiles)
1533*/
1534enum
1535{
1536   fdr99_f_program   = 0x01,   /* set for program files */
1537   fdr99_f_int      = 0x02,   /* set for binary files */
1538   fdr99_f_wp      = 0x08,   /* set if file is write-protected */
1539   /*fdr99_f_backup   = 0x10,*/   /* set if file has been modified since last backup */
1540   /*fdr99_f_dskimg   = 0x20,*/   /* set if file is a DSK image (HFDC HD only) */
1541   fdr99_f_var      = 0x80   /* set if file uses variable-length records*/
1542};
1543
1544/*
1545   DSK FDR record
1546*/
1547typedef struct dsk_fdr
1548{
1549   char name[10];         /* file name (10 characters, pad with spaces) */
1550   UINT16BE xreclen;      /* extended record len: if record len is >= 256, */
1551                        /* reclen is set to 0 and the actual reclen is */
1552                        /* stored here (Myarc HFDC only).  TI reserved */
1553                        /* this  field for data chain pointer extension, */
1554                        /* but this was never implemented. */
1555   UINT8 flags;         /* file status flags (see enum above) */
1556   UINT8 recsperphysrec;   /* logical records per physrec */
1557                        /* ignored for variable length record files and */
1558                        /* program files */
1559   UINT16BE fphysrecs;      /* file length in physrecs */
1560                        /* Note that the HFDC defines this field as the */
1561                        /* number of allocated physrecs in the cluster */
1562                        /* chain (i.e. rounded on the next AU */
1563                        /* boundary), so level-3 routines should use */
1564                        /* the fixrecs field instead to determine the */
1565                        /* logical lenght of field.  IIRC, the HFDC */
1566                        /* implementation is regarded as a bug because */
1567                        /* program files do not define the fixrecs field */
1568                        /* field, so program field saved by the HFDC */
1569                        /* DSR may be larger whan they should. */
1570   UINT8 eof;            /* EOF offset in last physrec for variable length */
1571                        /* record files and program files (0->256)*/
1572   UINT8 reclen;         /* logical record size in bytes ([1,255] 0->256) */
1573                        /* Maximum allowable record size for variable */
1574                        /* length record files.  Reserved for program */
1575                        /* files (set to 0).  Set to 0 if reclen >=256 */
1576                        /* (HFDC only). */
1577   UINT16LE fixrecs;      /* file length in logical records */
1578                        /* For variable length record files, number of */
1579                        /* 256-byte records actually used. */
1580   ti99_date_time creation;/* date and time of creation (HFDC and BwG only; */
1581                        /* reserved in TI) */
1582   ti99_date_time update;   /* date and time of last write to file (HFDC and */
1583                        /* BwG only; reserved in TI) */
1584   UINT8 clusters[76][3];   /* data cluster table: 0 through 76 entries (3 */
1585                        /* bytes each), one entry for each file cluster. */
1586                        /* 12 bits: address of first AU of cluster */
1587                        /* 12 bits: offset of last 256-byte record in cluster */
1588} dsk_fdr;
1589
1590/*
1591   WIN FDR record
1592*/
1593typedef struct win_fdr
1594{
1595   char name[10];         /* file name (10 characters, pad with spaces) */
1596   UINT16BE xreclen;      /* extended record len: if record len is >= 256, */
1597                        /* reclen is set to 0 and the actual reclen is */
1598                        /* stored here (Myarc HFDC only).  TI reserved */
1599                        /* this  field for data chain pointer extension, */
1600                        /* but this was never implemented. */
1601   UINT8 flags;         /* file status flags (see enum above) */
1602   UINT8 recsperphysrec;   /* logical records per physrec */
1603                        /* ignored for variable length record files and */
1604                        /* program files */
1605   UINT16BE fphysrecs_LSW;   /* eldest FDR: file length in physrecs */
1606                        /* Note that the HFDC defines this field as the */
1607                        /* number of allocated physrecs in the cluster */
1608                        /* chain (i.e. rounded on the next AU */
1609                        /* boundary), so level-3 routines should use */
1610                        /* the fixrecs field instead to determine the */
1611                        /* logical lenght of field.  IIRC, the HFDC */
1612                        /* implementation is regarded as a bug because */
1613                        /* program files do not define the fixrecs field */
1614                        /* field, so program field saved by the HFDC */
1615                        /* DSR may be larger whan they should. */
1616                     /* other sibling FDRs: index of the first file */
1617                        /* physrec in this particular sibling FDR */
1618   UINT8 eof;            /* EOF offset in last physrec for variable length */
1619                        /* record files and program files (0->256)*/
1620   UINT8 reclen;         /* logical record size in bytes ([1,255]) */
1621                        /* Maximum allowable record size for variable */
1622                        /* length record files.  Reserved for program */
1623                        /* files (set to 0).  Set to 0 if reclen >=256 */
1624                        /* (HFDC only). */
1625   UINT16LE fixrecs_LSW;   /* file length in logical records */
1626                        /* For variable length record files, number of */
1627                        /* 256-byte records actually used. */
1628   ti99_date_time creation;/* date and time of creation */
1629   ti99_date_time update;   /* date and time of last write to file */
1630
1631   char id[2];            /* 'FI' */
1632   UINT16BE prevsibFDR_AU;   /* address of the AU where previous sibling FDR is */
1633                        /* (see also xinfo_LSB) */
1634   UINT16BE nextsibFDR_AU;   /* address of the AU where next sibling FDR is */
1635                        /* (see also xinfo_LSB) */
1636   UINT16BE sibFDR_AUlen;   /* total number of data AUs allocated in this particular sibling FDR */
1637   UINT16BE parent_FDIR_AU;/* FDIR the file is listed in */
1638   UINT8 xinfo_MSB;      /* extended information (MSByte) */
1639                        /* bits 0-3: MSN of fphysrecs */
1640                        /* bits 4-7: MSN of fixrecs */
1641   UINT8 xinfo_LSB;      /* extended information (LSByte) */
1642                        /* bits 8-11: physrec offset within AU for */
1643                           /* previous sibling FDR (see prevsibFDR_AU) */
1644                        /* bits 12-15: physrec offset within AU for */
1645                           /* next sibling FDR (see nextsibFDR_AU) */
1646   UINT16BE clusters[54][2];/* data cluster table: 0 through 54 entries (4 */
1647                        /* bytes each), one entry for each file cluster. */
1648                        /* 16 bits: address of first AU of cluster */
1649                        /* 16 bits: address of last AU of cluster */
1650} win_fdr;
1651
1652/*
1653   tifile header: stand-alone file
1654*/
1655typedef struct tifile_header
1656{
1657   char tifiles[8];      /* always '\7TIFILES' */
1658   UINT16BE fphysrecs;      /* file length in physrecs */
1659   UINT8 flags;         /* see enum above */
1660   UINT8 recsperphysrec;   /* records per physrec */
1661   UINT8 eof;            /* current position of eof in last physrec (0->255)*/
1662   UINT8 reclen;         /* bytes per record ([1,255] 0->256) */
1663   UINT16BE fixrecs;      /* file length in records */
1664   UINT8 res[128-16];      /* reserved */
1665                        /* * variant a: */
1666                           /* 112 chars: 0xCA53 repeated 56 times */
1667                        /* * variant b: */
1668                           /* 4 chars: unknown */
1669                           /* 108 chars: 0xCA53 repeated 54 times */
1670                        /* * variant c: */
1671                           /* 10 chars: original TI file name filed with spaces */
1672                           /* 102 chars: spaces */
1673                        /* * variant d: */
1674                           /* 10 chars: original TI file name filed with spaces */
1675                           /* 2 chars: CR+LF */
1676                           /* 98 chars: spaces */
1677                           /* 2 chars: CR+LF */
1678                        /* * variant e: */
1679                           /* 10 chars: original TI file name */
1680                           /* 4 bytes: unknown */
1681                           /* 4 bytes: time & date of creation */
1682                           /* 4 bytes: time & date of last update */
1683                           /* 90 chars: spaces */
1684                        /* * variant f: */
1685                           /* 6 bytes: 'MYTERM' */
1686                           /* 4 bytes: time & date of creation */
1687                           /* 4 bytes: time & date of last update */
1688                           /* 2 bytes: unknown (always >0000) */
1689                           /* 96 chars: 0xCA53 repeated 56 times */
1690} tifile_header;
1691
1692/*
1693   level-2 file descriptor
1694*/
1695typedef struct ti99_lvl2_fileref_dsk
1696{
1697   ti99_lvl2_imgref *l2_img;
1698   int fdr_aphysrec;
1699   dsk_fdr fdr;
1700} ti99_lvl2_fileref_dsk;
1701
1702typedef struct ti99_lvl2_fileref_win
1703{
1704   ti99_lvl2_imgref *l2_img;
1705   unsigned fphysrecs;            /* copy of field in the eldest FDR */
1706   unsigned eldestfdr_aphysrec;   /* aphysrec address of the eldest FDR */
1707   unsigned curfdr_aphysrec;      /* aphysrec address of the currently open sibling FDR */
1708   win_fdr curfdr;               /* buffer with currently open sibling FDR */
1709} ti99_lvl2_fileref_win;
1710
1711typedef struct ti99_lvl2_fileref_tifiles
1712{
1713   imgtool_stream *file_handle;
1714   tifile_header hdr;
1715} ti99_lvl2_fileref_tifiles;
1716
1717typedef struct ti99_lvl2_fileref
1718{
1719   enum
1720   {
1721      L2F_DSK,
1722      L2F_WIN,
1723      L2F_TIFILES
1724   } type;
1725   union
1726   {
1727      ti99_lvl2_fileref_dsk dsk;
1728      ti99_lvl2_fileref_win win;
1729      ti99_lvl2_fileref_tifiles tifiles;
1730   } u;
1731} ti99_lvl2_fileref;
1732
1733
1734
1735/*
1736   Compare two (possibly empty) catalog entry for qsort
1737*/
1738static int cat_file_compare_qsort(const void *p1, const void *p2)
1739{
1740   const file_entry *entry1 = p1;
1741   const file_entry *entry2 = p2;
1742
1743   if ((entry1->fdr_ptr == 0) && (entry2->fdr_ptr == 0))
1744      return 0;
1745   else if (entry1->fdr_ptr == 0)
1746      return +1;
1747   else if (entry2->fdr_ptr == 0)
1748      return -1;
1749   else
1750      return memcmp(entry1->name, entry2->name, 10);
1751}
1752
1753static int cat_dir_compare_qsort(const void *p1, const void *p2)
1754{
1755   const dir_entry *entry1 = p1;
1756   const dir_entry *entry2 = p2;
1757
1758   if ((entry1->dir_ptr == 0) && (entry2->dir_ptr == 0))
1759      return 0;
1760   else if (entry1->dir_ptr == 0)
1761      return +1;
1762   else if (entry2->dir_ptr == 0)
1763      return -1;
1764   else
1765      return memcmp(entry1->name, entry2->name, 10);
1766}
1767
1768/*
1769   Read a directory catalog from disk image
1770
1771   l2_img: image reference
1772   aphysrec: physical record address of the FDIR
1773   dest: pointer to the destination buffer where the catalog should be written
1774
1775   Return an error code if there was an error, 0 otherwise.
1776*/
1777static int dsk_read_catalog(ti99_lvl2_imgref *l2_img, int aphysrec, ti99_catalog *dest)
1778{
1779   int totphysrecs = l2_img->u.dsk.totphysrecs;
1780   UINT16BE fdir_buf[128];
1781   dsk_fdr fdr;
1782   int i;
1783   int reply;
1784
1785
1786   /* Read FDIR record */
1787   reply = read_absolute_physrec(& l2_img->l1_img, aphysrec, fdir_buf);
1788   if (reply)
1789      return IMGTOOLERR_READERROR;
1790
1791   /* Copy FDIR info to catalog structure */
1792   for (i=0; i<128; i++)
1793      dest->files[i].fdr_ptr = get_UINT16BE(fdir_buf[i]);
1794
1795   /* Check FDIR pointers and check and extract file names from DDRs */
1796   for (i=0; i<128; i++)
1797   {
1798      if (dest->files[i].fdr_ptr >= totphysrecs)
1799      {
1800         return IMGTOOLERR_CORRUPTIMAGE;
1801      }
1802      else if (dest->files[i].fdr_ptr)
1803      {
1804         reply = read_absolute_physrec(& l2_img->l1_img, dest->files[i].fdr_ptr, &fdr);
1805         if (reply)
1806            return IMGTOOLERR_READERROR;
1807
1808         /* check and copy file name */
1809         if (check_fname(fdr.name))
1810            return IMGTOOLERR_CORRUPTIMAGE;
1811         memcpy(dest->files[i].name, fdr.name, 10);
1812      }
1813   }
1814
1815   /* Check catalog */
1816   for (i=0; i<127; i++)
1817   {
1818      if (((! dest->files[i].fdr_ptr) && dest->files[i+1].fdr_ptr)
1819         || ((dest->files[i].fdr_ptr && dest->files[i+1].fdr_ptr) && (memcmp(dest->files[i].name, dest->files[i+1].name, 10) >= 0)))
1820      {
1821         /* if the catalog is not sorted, we repair it */
1822         qsort(dest->files, sizeof(dest->files)/sizeof(dest->files[0]), sizeof(dest->files[0]),
1823               cat_file_compare_qsort);
1824         break;
1825      }
1826   }
1827
1828   /* Set file count */
1829   for (i=0; (i<128) && (dest->files[i].fdr_ptr != 0); i++)
1830      ;
1831   dest->num_files = i;
1832
1833   /* Set subdir count to 0 (subdirs are loaded elsewhere) */
1834   dest->num_subdirs = 0;
1835
1836   return 0;
1837}
1838
1839/*
1840   Read a directory catalog from disk image
1841
1842   l2_img: image reference
1843   DDR_AU: AU address of the VIB/DDR
1844   dest: pointer to the destination buffer where the catalog should be written
1845
1846   Return an error code if there was an error, 0 otherwise.
1847*/
1848static int win_read_catalog(ti99_lvl2_imgref *l2_img, int DDR_AU, ti99_catalog *dest)
1849{
1850   win_vib_ddr ddr_buf;
1851   UINT16BE fdir_buf[128];
1852   win_fdr fdr_buf;
1853   int i;
1854   int reply;
1855
1856
1857   /* Read DDR record */
1858   reply = read_absolute_physrec(& l2_img->l1_img, DDR_AU*l2_img->AUformat.physrecsperAU, &ddr_buf);
1859   if (reply)
1860      return IMGTOOLERR_READERROR;
1861
1862   /* sanity checks */
1863   if ((ddr_buf.num_files > 127) || (ddr_buf.num_subdirs > 114) || (get_UINT16BE(ddr_buf.fdir_AU) > l2_img->AUformat.totAUs))
1864      return IMGTOOLERR_CORRUPTIMAGE;
1865
1866   /* set file count and subdir count */
1867   dest->num_files = ddr_buf.num_files;
1868   dest->num_subdirs = ddr_buf.num_subdirs;
1869
1870   /* Copy DDR info to catalog structure */
1871   for (i=0; i<ddr_buf.num_subdirs; i++)
1872      dest->subdirs[i].dir_ptr = get_UINT16BE(ddr_buf.subdir_AU[i]);
1873
1874   /* Read FDIR record */
1875   reply = read_absolute_physrec(& l2_img->l1_img, get_UINT16BE(ddr_buf.fdir_AU)*l2_img->AUformat.physrecsperAU, fdir_buf);
1876   if (reply)
1877      return IMGTOOLERR_READERROR;
1878
1879   /* Copy FDIR info to catalog structure */
1880   for (i=0; i<dest->num_files; i++)
1881      dest->files[i].fdr_ptr = get_UINT16BE(fdir_buf[i]);
1882
1883   /* Check DDR pointers and check and extract file names from FDRs */
1884   for (i=0; i<dest->num_subdirs; i++)
1885   {
1886      if (dest->subdirs[i].dir_ptr >= l2_img->AUformat.totAUs)
1887      {
1888         return IMGTOOLERR_CORRUPTIMAGE;
1889      }
1890      else if (dest->subdirs[i].dir_ptr)
1891      {
1892         reply = read_absolute_physrec(& l2_img->l1_img, dest->subdirs[i].dir_ptr*l2_img->AUformat.physrecsperAU, &ddr_buf);
1893         if (reply)
1894            return IMGTOOLERR_READERROR;
1895
1896         /* check and copy file name */
1897         if (check_fname(ddr_buf.name))
1898            return IMGTOOLERR_CORRUPTIMAGE;
1899         memcpy(dest->subdirs[i].name, ddr_buf.name, 10);
1900      }
1901   }
1902
1903   /* Check FDIR pointers and check and extract file names from FDRs */
1904   for (i=0; i<dest->num_files; i++)
1905   {
1906      if (dest->files[i].fdr_ptr >= l2_img->AUformat.totAUs)
1907      {
1908         return IMGTOOLERR_CORRUPTIMAGE;
1909      }
1910      else if (dest->files[i].fdr_ptr)
1911      {
1912         reply = read_absolute_physrec(& l2_img->l1_img, dest->files[i].fdr_ptr*l2_img->AUformat.physrecsperAU, &fdr_buf);
1913         if (reply)
1914            return IMGTOOLERR_READERROR;
1915
1916         /* check and copy file name */
1917         if (check_fname(fdr_buf.name))
1918            return IMGTOOLERR_CORRUPTIMAGE;
1919         memcpy(dest->files[i].name, fdr_buf.name, 10);
1920      }
1921   }
1922
1923   /* Check catalog */
1924
1925   /* Check subdir order */
1926   for (i=0; i<dest->num_subdirs-1; i++)
1927   {
1928      if (((! dest->subdirs[i].dir_ptr) && dest->subdirs[i+1].dir_ptr)
1929         || ((dest->subdirs[i].dir_ptr && dest->subdirs[i+1].dir_ptr) && (memcmp(dest->subdirs[i].name, dest->subdirs[i+1].name, 10) >= 0)))
1930      {
1931         /* if the subdir catalog is not sorted, we repair it */
1932         qsort(dest->subdirs, dest->num_subdirs, sizeof(dest->subdirs[0]), cat_dir_compare_qsort);
1933         break;
1934      }
1935   }
1936
1937   /* Fix subdir count */
1938   while (dest->num_subdirs && (dest->subdirs[dest->num_subdirs-1].dir_ptr == 0))
1939      dest->num_subdirs--;
1940
1941   /* Check file order */
1942   for (i=0; i<dest->num_files-1; i++)
1943   {
1944      if (((! dest->files[i].fdr_ptr) && dest->files[i+1].fdr_ptr)
1945         || ((dest->files[i].fdr_ptr && dest->files[i+1].fdr_ptr) && (memcmp(dest->files[i].name, dest->files[i+1].name, 10) >= 0)))
1946      {
1947         /* if the file catalog is not sorted, we repair it */
1948         qsort(dest->files, dest->num_files, sizeof(dest->files[0]), cat_file_compare_qsort);
1949         break;
1950      }
1951   }
1952
1953   /* Fix file count */
1954   while (dest->num_files && (dest->files[dest->num_files-1].fdr_ptr == 0))
1955      dest->num_files--;
1956
1957   return 0;
1958}
1959
1960/*
1961   Search for a file path on a floppy image
1962
1963   l2_img: image reference
1964   fpath: path of the file to search
1965   parent_ref_valid: set to TRUE if either the file was found or the file was
1966      not found but its parent dir was
1967   parent_ref: reference to parent dir (0 for root)
1968   out_is_dir: TRUE if element is a directory
1969   catalog_index: on output, index of file catalog entry (may be NULL)
1970*/
1971static int dsk_find_catalog_entry(ti99_lvl2_imgref *l2_img, const char *fpath, int *parent_ref_valid, int *parent_ref, int *out_is_dir, int *catalog_index)
1972{
1973   int i;
1974   const ti99_catalog *cur_catalog;
1975   const char *element_start, *element_end;
1976   int element_len;
1977   char element[10];
1978   int is_dir = FALSE;
1979
1980
1981   cur_catalog = & l2_img->u.dsk.catalogs[0];
1982   if (parent_ref_valid)
1983      (* parent_ref_valid) = FALSE;
1984   if (parent_ref)
1985      *parent_ref = 0;
1986
1987   element_start = fpath;
1988   do
1989   {
1990      /* find next path element */
1991      element_end = strchr(element_start, '.');
1992      element_len = element_end ? (element_end - element_start) : strlen(element_start);
1993      if ((element_len > 10) || (element_len == 0))
1994         return IMGTOOLERR_BADFILENAME;
1995      /* last path element */
1996      if ((!element_end) && parent_ref_valid)
1997         (* parent_ref_valid) = TRUE;
1998
1999      /* generate file name */
2000      memcpy(element, element_start, element_len);
2001      memset(element+element_len, ' ', 10-element_len);
2002
2003      /* search entry in subdirectories */
2004      for (i = 0; i<cur_catalog->num_subdirs; i++)
2005      {
2006         if (! memcmp(element, cur_catalog->subdirs[i].name, 10))
2007         {
2008            is_dir = TRUE;
2009            break;
2010         }
2011      }
2012
2013      /* if it failed, search entry in files */
2014      if (i == cur_catalog->num_subdirs)
2015      {
2016         for (i = 0; i<cur_catalog->num_files; i++)
2017         {
2018            if (! memcmp(element, cur_catalog->files[i].name, 10))
2019            {
2020               is_dir = FALSE;
2021               break;
2022            }
2023         }
2024         /* exit if not found */
2025         if (i == cur_catalog->num_files)
2026         {
2027            return IMGTOOLERR_FILENOTFOUND;
2028         }
2029      }
2030
2031      /* iterate */
2032      if (element_end)
2033      {
2034         element_start = element_end+1;
2035
2036         if (! is_dir)
2037            /* this is not a directory */
2038            return IMGTOOLERR_BADFILENAME;
2039
2040         /* initialize cur_catalog */
2041         cur_catalog = & l2_img->u.dsk.catalogs[i+1];
2042         if (parent_ref)
2043            *parent_ref = i+1;
2044      }
2045      else
2046         element_start = NULL;
2047   }
2048   while (element_start);
2049
2050   if (out_is_dir)
2051      *out_is_dir = is_dir;
2052
2053   if (catalog_index)
2054      *catalog_index = i;
2055
2056   return 0;
2057}
2058
2059/*
2060   Search for a file path on a harddisk image
2061
2062   l2_img: image reference
2063   fpath: path of the file to search
2064   parent_ref_valid: set to TRUE if either the file was found or the file was
2065      not found but its parent dir was
2066   parent_ddr_AU: parent DDR AU address (0 for root)
2067   parent_catalog: catalog of parent dir (cannot be NULL)
2068   out_is_dir: TRUE if element is a directory
2069   catalog_index: on output, index of file catalog entry (may be NULL)
2070*/
2071static int win_find_catalog_entry(ti99_lvl2_imgref *l2_img, const char *fpath,
2072                           int *parent_ref_valid, int *parent_ddr_AU, ti99_catalog *parent_catalog,
2073                           int *out_is_dir, int *catalog_index)
2074{
2075   int i;
2076   const char *element_start, *element_end;
2077   int element_len;
2078   char element[10];
2079   int is_dir = FALSE;
2080   int errorcode;
2081
2082   if (parent_ref_valid)
2083      (* parent_ref_valid) = FALSE;
2084   if (parent_ddr_AU)
2085      *parent_ddr_AU = 0;
2086
2087   errorcode = win_read_catalog(l2_img, 0, parent_catalog);
2088   if (errorcode)
2089      return errorcode;
2090
2091   element_start = fpath;
2092   do
2093   {
2094      /* find next path element */
2095      element_end = strchr(element_start, '.');
2096      element_len = element_end ? (element_end - element_start) : strlen(element_start);
2097      if ((element_len > 10) || (element_len == 0))
2098         return IMGTOOLERR_BADFILENAME;
2099      /* last path element */
2100      if ((!element_end) && parent_ref_valid)
2101         (* parent_ref_valid) = TRUE;
2102
2103      /* generate file name */
2104      memcpy(element, element_start, element_len);
2105      memset(element+element_len, ' ', 10-element_len);
2106
2107      /* search entry in subdirectories */
2108      for (i = 0; i<parent_catalog->num_subdirs; i++)
2109      {
2110         if (! memcmp(element, parent_catalog->subdirs[i].name, 10))
2111         {
2112            is_dir = TRUE;
2113            break;
2114         }
2115      }
2116
2117      /* if it failed, search entry in files */
2118      if (i == parent_catalog->num_subdirs)
2119      {
2120         for (i = 0; i<parent_catalog->num_files; i++)
2121         {
2122            if (! memcmp(element, parent_catalog->files[i].name, 10))
2123            {
2124               is_dir = FALSE;
2125               break;
2126            }
2127         }
2128         /* exit if not found */
2129         if (i == parent_catalog->num_files)
2130         {
2131            return IMGTOOLERR_FILENOTFOUND;
2132         }
2133      }
2134
2135      /* iterate */
2136      if (element_end)
2137      {
2138         element_start = element_end+1;
2139
2140         if (! is_dir)
2141            /* this is not a directory */
2142            return IMGTOOLERR_BADFILENAME;
2143
2144         if (parent_ddr_AU)
2145            *parent_ddr_AU = parent_catalog->subdirs[i].dir_ptr;
2146
2147         errorcode = win_read_catalog(l2_img, parent_catalog->subdirs[i].dir_ptr, parent_catalog);
2148         if (errorcode)
2149            return errorcode;
2150      }
2151      else
2152         element_start = NULL;
2153   }
2154   while (element_start);
2155
2156   if (out_is_dir)
2157      *out_is_dir = is_dir;
2158
2159   if (catalog_index)
2160      *catalog_index = i;
2161
2162   return 0;
2163}
2164
2165/*
2166   Allocate one AU on disk, for use as a fdr record
2167
2168   l2_img: image reference
2169   fdr_AU: on output, address of allocated AU
2170*/
2171static int alloc_fdr_AU(ti99_lvl2_imgref *l2_img, unsigned *fdr_AU)
2172{
2173   int totAUs = l2_img->AUformat.totAUs;
2174   int i;
2175
2176   for (i=0; i<totAUs; i++)
2177   {
2178      if (! (l2_img->abm[i >> 3] & (1 << (i & 7))))
2179      {
2180         *fdr_AU = i;
2181         l2_img->abm[i >> 3] |= 1 << (i & 7);
2182
2183         return 0;
2184      }
2185   }
2186
2187   return IMGTOOLERR_NOSPACE;
2188}
2189
2190INLINE int get_dsk_fdr_cluster_baseAU(ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index)
2191{
2192   int reply;
2193
2194   /* read base AU/physrec for this cluster */
2195   reply = ((fdr->clusters[cluster_index][1] & 0xf) << 8) | fdr->clusters[cluster_index][0];
2196   /* convert to AU address */
2197   if (l2_img->AUformat.physrecsperAU <= 2)
2198      reply /= l2_img->AUformat.physrecsperAU;
2199
2200   return reply;
2201}
2202
2203INLINE int get_dsk_fdr_cluster_baseaphysrec(ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index)
2204{
2205   int reply;
2206
2207   /* read base AU/physrec for this cluster */
2208   reply = ((fdr->clusters[cluster_index][1] & 0xf) << 8) | fdr->clusters[cluster_index][0];
2209   /* convert to physrec address */
2210   if (l2_img->AUformat.physrecsperAU > 2)
2211      reply *= l2_img->AUformat.physrecsperAU;
2212
2213   return reply;
2214}
2215
2216INLINE int get_dsk_fdr_cluster_lastfphysrec(dsk_fdr *fdr, int cluster_index)
2217{
2218   return (fdr->clusters[cluster_index][2] << 4) | (fdr->clusters[cluster_index][1] >> 4);
2219}
2220
2221INLINE void set_dsk_fdr_cluster_lastfphysrec(dsk_fdr *fdr, int cluster_index, int data)
2222{
2223   fdr->clusters[cluster_index][1] = (fdr->clusters[cluster_index][1] & 0x0f) | (data << 4);
2224   fdr->clusters[cluster_index][2] = data >> 4;
2225}
2226
2227INLINE void set_dsk_fdr_cluster(ti99_lvl2_imgref *l2_img, dsk_fdr *fdr, int cluster_index, int baseAU, int lastfphysrec)
2228{
2229   /* convert AU address to FDR value */
2230   if (l2_img->AUformat.physrecsperAU <= 2)
2231      baseAU *= l2_img->AUformat.physrecsperAU;
2232
2233   /* write cluster entry */
2234   fdr->clusters[cluster_index][0] = baseAU;
2235   fdr->clusters[cluster_index][1] = ((baseAU >> 8) & 0x0f) | (lastfphysrec << 4);
2236   fdr->clusters[cluster_index][2] = lastfphysrec >> 4;
2237}
2238
2239INLINE unsigned get_win_fdr_fphysrecs(win_fdr *fdr)
2240{
2241   return (((unsigned) fdr->xinfo_MSB << 12) & 0xf0000) | get_UINT16BE(fdr->fphysrecs_LSW);
2242}
2243
2244INLINE void set_win_fdr_fphysrecs(win_fdr *fdr, unsigned data)
2245{
2246   fdr->xinfo_MSB = (fdr->xinfo_MSB & 0x0f) | ((data >> 12) & 0xf0);
2247   set_UINT16BE(&fdr->fphysrecs_LSW, data & 0xffff);
2248}
2249
2250INLINE unsigned get_win_fdr_fixrecs(win_fdr *fdr)
2251{
2252   return (((unsigned) fdr->xinfo_MSB << 16) & 0xf0000) | get_UINT16LE(fdr->fixrecs_LSW);
2253}
2254
2255INLINE void set_win_fdr_fixrecs(win_fdr *fdr, unsigned data)
2256{
2257   fdr->xinfo_MSB = (fdr->xinfo_MSB & 0xf0) | ((data >> 16) & 0x0f);
2258   set_UINT16LE(&fdr->fixrecs_LSW, data & 0xffff);
2259}
2260
2261INLINE unsigned get_win_fdr_prevsibFDR_aphysrec(ti99_lvl2_imgref *l2_img, win_fdr *fdr)
2262{
2263   unsigned prevsibFDR_AU = get_UINT16BE(fdr->prevsibFDR_AU);
2264
2265   return prevsibFDR_AU
2266         ? (prevsibFDR_AU * l2_img->AUformat.physrecsperAU + ((fdr->xinfo_LSB >> 4) & 0xf))
2267         : 0;
2268}
2269
2270INLINE unsigned get_win_fdr_nextsibFDR_aphysrec(ti99_lvl2_imgref *l2_img, win_fdr *fdr)
2271{
2272   unsigned nextsibFDR_AU = get_UINT16BE(fdr->nextsibFDR_AU);
2273
2274   return nextsibFDR_AU
2275         ? (nextsibFDR_AU * l2_img->AUformat.physrecsperAU + (fdr->xinfo_LSB & 0xf))
2276         : 0;
2277}
2278
2279INLINE unsigned get_win_fdr_cursibFDR_basefphysrec(win_fdr *fdr)
2280{
2281   return get_UINT16BE(fdr->prevsibFDR_AU) ? get_win_fdr_fphysrecs(fdr) : 0;
2282}
2283
2284/*
2285   Advance to next sibling FDR
2286*/
2287static int win_goto_next_sibFDR(ti99_lvl2_fileref_win *win_file)
2288{
2289   if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) == 0)
2290      return IMGTOOLERR_UNEXPECTED;
2291
2292   win_file->curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(win_file->l2_img, &win_file->curfdr);
2293   if (read_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2294      return IMGTOOLERR_READERROR;
2295
2296   return 0;
2297}
2298
2299/*
2300   Back to previous sibling FDR
2301*/
2302static int win_goto_prev_sibFDR(ti99_lvl2_fileref_win *win_file)
2303{
2304   if (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) == 0)
2305      return IMGTOOLERR_UNEXPECTED;
2306
2307   win_file->curfdr_aphysrec = get_win_fdr_prevsibFDR_aphysrec(win_file->l2_img, &win_file->curfdr);
2308   if (read_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2309      return IMGTOOLERR_READERROR;
2310
2311   return 0;
2312}
2313
2314/*
2315   Append a new sibling FDR at the end of the sibling FDR list, and open it.
2316
2317   You must have gone to the end of the list.
2318*/
2319static int win_alloc_sibFDR(ti99_lvl2_fileref_win *win_file)
2320{
2321   unsigned oldfdr_AU, oldfdr_physrecinAU;
2322   unsigned newfdr_AU, newfdr_physrecinAU;
2323   int allocated = FALSE;
2324   int errorcode;
2325   unsigned cursibFDR_basefphysrec;
2326
2327   if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU))
2328      return IMGTOOLERR_UNEXPECTED;
2329
2330   oldfdr_AU = win_file->curfdr_aphysrec / win_file->l2_img->AUformat.physrecsperAU;
2331   oldfdr_physrecinAU = win_file->curfdr_aphysrec % win_file->l2_img->AUformat.physrecsperAU;
2332
2333   if (oldfdr_physrecinAU != (win_file->l2_img->AUformat.physrecsperAU - 1))
2334   {   /* current AU is not full */
2335      newfdr_AU = oldfdr_AU;
2336      newfdr_physrecinAU = oldfdr_physrecinAU + 1;
2337   }
2338   else
2339   {   /* current AU is full: allocate another */
2340      errorcode = alloc_fdr_AU(win_file->l2_img, &newfdr_AU);
2341      if (errorcode)
2342         return errorcode;
2343      newfdr_physrecinAU = 0;
2344      allocated = TRUE;
2345   }
2346
2347   set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, newfdr_AU);
2348   win_file->curfdr.xinfo_LSB = (win_file->curfdr.xinfo_LSB & 0xf0) | newfdr_physrecinAU;
2349
2350   /* save current sibling FDR */
2351   if (write_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2352   {
2353      /* clear pointer */
2354      set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, 0);
2355      win_file->curfdr.xinfo_LSB = win_file->curfdr.xinfo_LSB & 0xf0;
2356      if (allocated)
2357         /* free AU */
2358         win_file->l2_img->abm[newfdr_AU >> 3] |= 1 << (newfdr_AU & 7);
2359      return IMGTOOLERR_WRITEERROR;
2360   }
2361
2362   /* now update in-memory structure to describe new sibling FDR */
2363   cursibFDR_basefphysrec = get_win_fdr_cursibFDR_basefphysrec(&win_file->curfdr)
2364                        + get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU;
2365
2366   set_UINT16BE(&win_file->curfdr.nextsibFDR_AU, 0);
2367   set_UINT16BE(&win_file->curfdr.prevsibFDR_AU, oldfdr_AU);
2368   win_file->curfdr.xinfo_LSB = oldfdr_physrecinAU << 4;
2369
2370   win_file->curfdr_aphysrec = newfdr_AU * win_file->l2_img->AUformat.physrecsperAU + newfdr_physrecinAU;
2371
2372   set_win_fdr_fphysrecs(&win_file->curfdr, cursibFDR_basefphysrec);
2373   set_UINT16BE(&win_file->curfdr.sibFDR_AUlen, 0);
2374   memset(win_file->curfdr.clusters, 0, sizeof(win_file->curfdr.clusters));
2375
2376   return 0;
2377}
2378
2379/*
2380   Extend a file with nb_alloc_physrecs extra physrecs
2381
2382   dsk_file: file reference
2383   nb_alloc_physrecs: number of physical records to allocate
2384*/
2385static int dsk_alloc_file_physrecs(ti99_lvl2_fileref_dsk *dsk_file, int nb_alloc_physrecs)
2386{
2387   int totAUs = dsk_file->l2_img->AUformat.totAUs;
2388   int free_physrecs;
2389   int fphysrecs;
2390   int i;
2391   int cluster_index;
2392   int last_sec, p_last_sec = 0;
2393   int cur_block_seclen;
2394   int cluster_baseAU, cluster_AUlen;
2395   int first_best_block_baseAU = 0, first_best_block_seclen;
2396   int second_best_block_baseAU = 0, second_best_block_seclen;
2397   int search_start;
2398
2399   /* compute free space */
2400   free_physrecs = 0;
2401   for (i=0; i<totAUs; i++)
2402   {
2403      if (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2404         free_physrecs += dsk_file->l2_img->AUformat.physrecsperAU;
2405   }
2406
2407   /* check we have enough free space */
2408   if (free_physrecs < nb_alloc_physrecs)
2409      return IMGTOOLERR_NOSPACE;
2410
2411   /* current number of data physrecs in file */
2412   fphysrecs = get_UINT16BE(dsk_file->fdr.fphysrecs);
2413
2414   if (fphysrecs == 0)
2415   {   /* cluster array must be empty */
2416      cluster_index = 0;
2417   }
2418   else
2419   {   /* try to extend last block */
2420      last_sec = -1;
2421      for (cluster_index=0; cluster_index<76; cluster_index++)
2422      {
2423         p_last_sec = last_sec;
2424         last_sec = get_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index);
2425         if (last_sec >= (fphysrecs-1))
2426            break;
2427      }
2428      if (cluster_index == 76)
2429         /* that sucks */
2430         return IMGTOOLERR_CORRUPTIMAGE;
2431
2432      if (last_sec > (fphysrecs-1))
2433      {   /* some extra space has already been allocated */
2434         cur_block_seclen = last_sec - (fphysrecs-1);
2435         if (cur_block_seclen > nb_alloc_physrecs)
2436            cur_block_seclen = nb_alloc_physrecs;
2437
2438         fphysrecs += cur_block_seclen;
2439         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2440         nb_alloc_physrecs -= cur_block_seclen;
2441         if (! nb_alloc_physrecs)
2442            return 0;   /* done */
2443      }
2444
2445      /* round up to next AU boundary */
2446      last_sec = last_sec + dsk_file->l2_img->AUformat.physrecsperAU - (last_sec % dsk_file->l2_img->AUformat.physrecsperAU) - 1;
2447
2448      if (last_sec > (fphysrecs-1))
2449      {   /* some extra space has already been allocated */
2450         cur_block_seclen = last_sec - (fphysrecs-1);
2451         if (cur_block_seclen > nb_alloc_physrecs)
2452            cur_block_seclen = nb_alloc_physrecs;
2453
2454         fphysrecs += cur_block_seclen;
2455         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2456         set_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index, fphysrecs-1);
2457         nb_alloc_physrecs -= cur_block_seclen;
2458         if (! nb_alloc_physrecs)
2459            return 0;   /* done */
2460      }
2461
2462      /* read base AU address for this cluster */
2463      cluster_baseAU = get_dsk_fdr_cluster_baseAU(dsk_file->l2_img, &dsk_file->fdr, cluster_index);
2464      /* point past cluster end */
2465      cluster_baseAU += (last_sec-p_last_sec/*+file->l2_img->AUformat.physrecsperAU-1*/) / dsk_file->l2_img->AUformat.physrecsperAU;
2466      /* count free physrecs after last block */
2467      cur_block_seclen = 0;
2468      for (i=cluster_baseAU; (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7)))) && (cur_block_seclen < nb_alloc_physrecs) && (i < totAUs); i++)
2469         cur_block_seclen += dsk_file->l2_img->AUformat.physrecsperAU;
2470      if (cur_block_seclen)
2471      {   /* extend last block */
2472         if (cur_block_seclen > nb_alloc_physrecs)
2473            cur_block_seclen = nb_alloc_physrecs;
2474
2475         fphysrecs += cur_block_seclen;
2476         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2477         last_sec += cur_block_seclen;
2478         nb_alloc_physrecs -= cur_block_seclen;
2479         set_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index, last_sec);
2480         cluster_AUlen = (cur_block_seclen + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
2481         for (i=0; i<cluster_AUlen; i++)
2482            dsk_file->l2_img->abm[(i+cluster_baseAU) >> 3] |= 1 << ((i+cluster_baseAU) & 7);
2483         if (! nb_alloc_physrecs)
2484            return 0;   /* done */
2485      }
2486      cluster_index++;
2487      if (cluster_index == 76)
2488         /* that sucks */
2489         return IMGTOOLERR_NOSPACE;
2490   }
2491
2492   search_start = dsk_file->l2_img->data_offset;   /* initially, search for free space only in data space */
2493   while (nb_alloc_physrecs)
2494   {
2495      /* find smallest data block at least nb_alloc_physrecs in lenght, and largest data block less than nb_alloc_physrecs in lenght */
2496      first_best_block_seclen = INT_MAX;
2497      second_best_block_seclen = 0;
2498      for (i=search_start; i<totAUs; i++)
2499      {
2500         if (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2501         {   /* found one free block */
2502            /* compute its lenght */
2503            cluster_baseAU = i;
2504            cur_block_seclen = 0;
2505            while ((i<totAUs) && (! (dsk_file->l2_img->abm[i >> 3] & (1 << (i & 7)))))
2506            {
2507               cur_block_seclen += dsk_file->l2_img->AUformat.physrecsperAU;
2508               i++;
2509            }
2510            /* compare to previous best and second-best blocks */
2511            if ((cur_block_seclen < first_best_block_seclen) && (cur_block_seclen >= nb_alloc_physrecs))
2512            {
2513               first_best_block_baseAU = cluster_baseAU;
2514               first_best_block_seclen = cur_block_seclen;
2515               if (cur_block_seclen == nb_alloc_physrecs)
2516                  /* no need to search further */
2517                  break;
2518            }
2519            else if ((cur_block_seclen > second_best_block_seclen) && (cur_block_seclen < nb_alloc_physrecs))
2520            {
2521               second_best_block_baseAU = cluster_baseAU;
2522               second_best_block_seclen = cur_block_seclen;
2523            }
2524         }
2525      }
2526
2527      if (first_best_block_seclen != INT_MAX)
2528      {   /* found one contiguous block which can hold it all */
2529         fphysrecs += nb_alloc_physrecs;
2530         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2531
2532         set_dsk_fdr_cluster(dsk_file->l2_img, &dsk_file->fdr, cluster_index, first_best_block_baseAU, fphysrecs-1);
2533         cluster_AUlen = (nb_alloc_physrecs + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
2534         for (i=0; i<cluster_AUlen; i++)
2535            dsk_file->l2_img->abm[(i+first_best_block_baseAU) >> 3] |= 1 << ((i+first_best_block_baseAU) & 7);
2536
2537         nb_alloc_physrecs = 0;
2538      }
2539      else if (second_best_block_seclen != 0)
2540      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
2541         fphysrecs += second_best_block_seclen;
2542         set_UINT16BE(& dsk_file->fdr.fphysrecs, fphysrecs);
2543
2544         set_dsk_fdr_cluster(dsk_file->l2_img, &dsk_file->fdr, cluster_index, second_best_block_baseAU, fphysrecs-1);
2545         cluster_AUlen = (second_best_block_seclen + dsk_file->l2_img->AUformat.physrecsperAU - 1) / dsk_file->l2_img->AUformat.physrecsperAU;
2546         for (i=0; i<cluster_AUlen; i++)
2547            dsk_file->l2_img->abm[(i+second_best_block_baseAU) >> 3] |= 1 << ((i+second_best_block_baseAU) & 7);
2548
2549         nb_alloc_physrecs -= second_best_block_seclen;
2550
2551         cluster_index++;
2552         if (cluster_index == 76)
2553            /* that sucks */
2554            return IMGTOOLERR_NOSPACE;
2555      }
2556      else if (search_start != 0)
2557      {   /* we did not find any free physrec in the data section of the disk */
2558         search_start = 0;   /* time to fall back to fdr space */
2559      }
2560      else
2561         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
2562   }
2563
2564   return 0;
2565}
2566
2567/*
2568   Extend a file with nb_alloc_physrecs extra physrecs
2569
2570   win_file: file reference
2571   nb_alloc_physrecs: number of physical records to allocate
2572*/
2573static int win_alloc_file_physrecs(ti99_lvl2_fileref_win *win_file, int nb_alloc_physrecs)
2574{
2575   int totAUs = win_file->l2_img->AUformat.totAUs;
2576   int free_physrecs;
2577   int fphysrecs;
2578   int i;
2579   int cluster_index;
2580   int num_fphysrec;
2581   int cur_block_seclen;
2582   int cluster_baseAU, cluster_AUlen;
2583   int first_best_block_baseAU = 0, first_best_block_seclen;
2584   int second_best_block_baseAU = 0, second_best_block_seclen;
2585   int search_start;
2586   int errorcode;
2587
2588   /* compute free space */
2589   free_physrecs = 0;
2590   for (i=0; i<totAUs; i++)
2591   {
2592      if (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2593         free_physrecs += win_file->l2_img->AUformat.physrecsperAU;
2594   }
2595
2596   /* check we have enough free space */
2597   if (free_physrecs < nb_alloc_physrecs)
2598      return IMGTOOLERR_NOSPACE;
2599
2600   /* move to last sibling non-empty FDR */
2601   while ((get_UINT16BE(win_file->curfdr.nextsibFDR_AU) != 0) &&
2602            (get_UINT16BE(win_file->curfdr.clusters[53][0]) != 0))
2603   {
2604      errorcode = win_goto_next_sibFDR(win_file);
2605      if (errorcode)
2606         return errorcode;
2607   }
2608   if ((get_UINT16BE(win_file->curfdr.clusters[0][0]) == 0) && (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) != 0))
2609   {   /* this is annoying: we have found a sibling FDR filled with 0s: rewind
2610      to last non-empty sibling if applicable */
2611      errorcode = win_goto_prev_sibFDR(win_file);
2612      if (errorcode)
2613         return errorcode;
2614   }
2615
2616   /* current number of data physrecs in file */
2617   fphysrecs = win_file->fphysrecs;
2618
2619   /* current number of allocated physrecs */
2620   num_fphysrec = get_win_fdr_cursibFDR_basefphysrec(&win_file->curfdr)
2621                  + get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU;
2622
2623   if (num_fphysrec > fphysrecs)
2624   {   /* some extra space has already been allocated */
2625      cur_block_seclen = num_fphysrec - fphysrecs;
2626      if (cur_block_seclen > nb_alloc_physrecs)
2627         cur_block_seclen = nb_alloc_physrecs;
2628
2629      fphysrecs += cur_block_seclen;
2630      win_file->fphysrecs = fphysrecs;
2631      /* TODO: update eldest FDR fphysrecs field */
2632      /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2633      nb_alloc_physrecs -= cur_block_seclen;
2634      if (! nb_alloc_physrecs)
2635         return 0;   /* done */
2636   }
2637
2638   /* find last non-empty cluster */
2639   for (cluster_index=0; (cluster_index<54) && (get_UINT16BE(win_file->curfdr.clusters[cluster_index][0]) != 0); cluster_index++)
2640      ;
2641   /* if we are dealing with an empty file, we will have (cluster_index == 0)... */
2642   if (cluster_index != 0)
2643   {
2644      cluster_index--;
2645      /* try to extend last cluster */
2646      /* point past cluster end */
2647      cluster_baseAU = get_UINT16BE(win_file->curfdr.clusters[cluster_index][1]) + 1;
2648      /* count free physrecs after last block */
2649      cur_block_seclen = 0;
2650      for (i=cluster_baseAU; (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7)))) && (cur_block_seclen < nb_alloc_physrecs) && (i < totAUs); i++)
2651         cur_block_seclen += win_file->l2_img->AUformat.physrecsperAU;
2652      if (cur_block_seclen)
2653      {   /* extend last block */
2654         if (cur_block_seclen > nb_alloc_physrecs)
2655            cur_block_seclen = nb_alloc_physrecs;
2656
2657         fphysrecs += cur_block_seclen;
2658         cluster_AUlen = (cur_block_seclen + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
2659         win_file->fphysrecs = fphysrecs;
2660         /* TODO: update eldest FDR fphysrecs field */
2661         /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2662         set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
2663                     get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
2664         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
2665                     get_UINT16BE(win_file->curfdr.clusters[cluster_index][1])+cluster_AUlen);
2666         for (i=0; i<cluster_AUlen; i++)
2667            win_file->l2_img->abm[(i+cluster_baseAU) >> 3] |= 1 << ((i+cluster_baseAU) & 7);
2668         nb_alloc_physrecs -= cur_block_seclen;
2669         if (! nb_alloc_physrecs)
2670            return 0;   /* done */
2671      }
2672      /* now point to first free entry in cluster table */
2673      cluster_index++;
2674   }
2675
2676   search_start = win_file->l2_img->data_offset;   /* initially, search for free space only in data space */
2677   while (nb_alloc_physrecs)
2678   {
2679      /* find smallest data block at least nb_alloc_physrecs in lenght, and largest data block less than nb_alloc_physrecs in lenght */
2680      first_best_block_seclen = INT_MAX;
2681      second_best_block_seclen = 0;
2682      for (i=search_start; i<totAUs; i++)
2683      {
2684         if (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7))))
2685         {   /* found one free block */
2686            /* compute its lenght */
2687            cluster_baseAU = i;
2688            cur_block_seclen = 0;
2689            while ((i<totAUs) && (! (win_file->l2_img->abm[i >> 3] & (1 << (i & 7)))))
2690            {
2691               cur_block_seclen += win_file->l2_img->AUformat.physrecsperAU;
2692               i++;
2693            }
2694            /* compare to previous best and second-best blocks */
2695            if ((cur_block_seclen < first_best_block_seclen) && (cur_block_seclen >= nb_alloc_physrecs))
2696            {
2697               first_best_block_baseAU = cluster_baseAU;
2698               first_best_block_seclen = cur_block_seclen;
2699               if (cur_block_seclen == nb_alloc_physrecs)
2700                  /* no need to search further */
2701                  break;
2702            }
2703            else if ((cur_block_seclen > second_best_block_seclen) && (cur_block_seclen < nb_alloc_physrecs))
2704            {
2705               second_best_block_baseAU = cluster_baseAU;
2706               second_best_block_seclen = cur_block_seclen;
2707            }
2708         }
2709      }
2710
2711      if ((first_best_block_seclen != INT_MAX) || (second_best_block_seclen != 0))
2712      {
2713         if (cluster_index == 54)
2714         {
2715            /* end of cluster list: go to next sibling FDR */
2716            if (write_absolute_physrec(& win_file->l2_img->l1_img, win_file->curfdr_aphysrec, &win_file->curfdr))
2717               return IMGTOOLERR_WRITEERROR;
2718            if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) != 0)
2719            {   /* read next sibling FDR */
2720               errorcode = win_goto_next_sibFDR(win_file);
2721               if (errorcode)
2722                  return errorcode;
2723            }
2724            else
2725            {   /* allocate new sibling FDR */
2726               errorcode = win_alloc_sibFDR(win_file);
2727               if (errorcode)
2728                  return errorcode;
2729            }
2730            cluster_index = 0;
2731         }
2732      }
2733
2734      if (first_best_block_seclen != INT_MAX)
2735      {   /* found one contiguous block which can hold it all */
2736         fphysrecs += nb_alloc_physrecs;
2737         cluster_AUlen = (nb_alloc_physrecs + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
2738         win_file->fphysrecs = fphysrecs;
2739         /* TODO: update eldest FDR fphysrecs field */
2740         /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2741         set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
2742                        get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
2743         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][0], first_best_block_baseAU);
2744         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
2745                        first_best_block_baseAU+cluster_AUlen-1);
2746
2747         for (i=0; i<cluster_AUlen; i++)
2748            win_file->l2_img->abm[(i+first_best_block_baseAU) >> 3] |= 1 << ((i+first_best_block_baseAU) & 7);
2749
2750         nb_alloc_physrecs = 0;
2751      }
2752      else if (second_best_block_seclen != 0)
2753      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
2754         fphysrecs += second_best_block_seclen;
2755         cluster_AUlen = (second_best_block_seclen + win_file->l2_img->AUformat.physrecsperAU - 1) / win_file->l2_img->AUformat.physrecsperAU;
2756         win_file->fphysrecs = fphysrecs;
2757         /* TODO: update eldest FDR fphysrecs field */
2758         /*set_win_fdr_fphysrecs(& win_file->rootfdr.fphysrecs, fphysrecs);*/
2759         set_UINT16BE(&win_file->curfdr.sibFDR_AUlen,
2760                        get_UINT16BE(win_file->curfdr.sibFDR_AUlen)+cluster_AUlen);
2761         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][0], second_best_block_baseAU);
2762         set_UINT16BE(&win_file->curfdr.clusters[cluster_index][1],
2763                        second_best_block_baseAU+cluster_AUlen-1);
2764
2765         for (i=0; i<cluster_AUlen; i++)
2766            win_file->l2_img->abm[(i+second_best_block_baseAU) >> 3] |= 1 << ((i+second_best_block_baseAU) & 7);
2767
2768         nb_alloc_physrecs -= second_best_block_seclen;
2769
2770         /* now point to first free entry in cluster table */
2771         cluster_index++;
2772      }
2773      else if (search_start != 0)
2774      {   /* we did not find any free physrec in the data section of the disk */
2775         search_start = 0;   /* time to fall back to fdr space */
2776      }
2777      else
2778         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
2779   }
2780
2781   return 0;
2782}
2783
2784/*
2785   Allocate a new (empty) file
2786*/
2787static int new_file_lvl2_dsk(ti99_lvl2_imgref *l2_img, int parent_ref, char filename[10], ti99_lvl2_fileref *l2_file)
2788{
2789   ti99_catalog *catalog = &l2_img->u.dsk.catalogs[parent_ref];
2790   unsigned fdr_AU, fdr_aphysrec;
2791   int catalog_index, i;
2792   int reply = 0;
2793   int errorcode;
2794
2795
2796   if (catalog->num_files >= 127)
2797      /* if num_files == 128, catalog is full */
2798      /* if num_files == 127, catalog is not full, but we don't want to write
2799      a 128th entry for compatibility with some existing DSRs that detect the
2800      end of the FDIR array with a 0 entry (and do not check that the index
2801      has not reached 128) */
2802      return IMGTOOLERR_NOSPACE;
2803
2804   /* find insertion point in catalog */
2805   for (i=0; (i < catalog->num_files) && ((reply = memcmp(catalog->files[i].name, filename, 10)) < 0); i++)
2806      ;
2807
2808   if ((i<catalog->num_files) && (reply == 0))
2809      /* file already exists */
2810      return IMGTOOLERR_BADFILENAME;
2811   else
2812   {
2813      /* otherwise insert new entry */
2814      catalog_index = i;
2815      errorcode = alloc_fdr_AU(l2_img, &fdr_AU);
2816      if (errorcode)
2817         return errorcode;
2818      fdr_aphysrec = fdr_AU * l2_img->AUformat.physrecsperAU;
2819
2820      /* shift catalog entries until the insertion point */
2821      for (i=catalog->num_files; i>catalog_index; i--)
2822         catalog->files[i] = catalog->files[i-1];
2823
2824      /* write new catalog entry */
2825      catalog->files[catalog_index].fdr_ptr = fdr_aphysrec;
2826      memcpy(catalog->files[catalog_index].name, filename, 10);
2827
2828      /* update catalog len */
2829      catalog->num_files++;
2830   }
2831
2832   /* set up file handle */
2833   l2_file->type = L2F_DSK;
2834   l2_file->u.dsk.l2_img = l2_img;
2835   l2_file->u.dsk.fdr_aphysrec = fdr_aphysrec;
2836   memset(&l2_file->u.dsk.fdr, 0, sizeof(l2_file->u.dsk.fdr));
2837   memcpy(l2_file->u.dsk.fdr.name, filename, 10);
2838
2839   return 0;
2840}
2841
2842/*
2843   Allocate a new (empty) file
2844*/
2845static int new_file_lvl2_win(ti99_lvl2_imgref *l2_img, ti99_catalog *parent_catalog, char filename[10], ti99_lvl2_fileref *l2_file)
2846{
2847   unsigned fdr_AU;
2848   int catalog_index, i;
2849   int reply = 0;
2850   int errorcode;
2851
2852
2853   if (parent_catalog->num_files >= 127)
2854      /* if num_files == 127, catalog is full */
2855      return IMGTOOLERR_NOSPACE;
2856
2857   /* find insertion point in catalog */
2858   for (i=0; (i < parent_catalog->num_files) && ((reply = memcmp(parent_catalog->files[i].name, filename, 10)) < 0); i++)
2859      ;
2860
2861   if ((i<parent_catalog->num_files) && (reply == 0))
2862      /* file already exists */
2863      return IMGTOOLERR_BADFILENAME;
2864   else
2865   {
2866      /* otherwise insert new entry */
2867      catalog_index = i;
2868      errorcode = alloc_fdr_AU(l2_img, &fdr_AU);
2869      if (errorcode)
2870         return errorcode;
2871
2872      /* shift catalog entries until the insertion point */
2873      for (i=parent_catalog->num_files; i>catalog_index; i--)
2874         parent_catalog->files[i] = parent_catalog->files[i-1];
2875
2876      /* write new catalog entry */
2877      parent_catalog->files[catalog_index].fdr_ptr = fdr_AU;
2878      memcpy(parent_catalog->files[catalog_index].name, filename, 10);
2879
2880      /* update catalog len */
2881      parent_catalog->num_files++;
2882   }
2883
2884   /* set up file handle */
2885   l2_file->type = L2F_WIN;
2886   l2_file->u.win.l2_img = l2_img;
2887   l2_file->u.win.fphysrecs = 0;
2888   l2_file->u.win.eldestfdr_aphysrec = fdr_AU * l2_img->AUformat.physrecsperAU;
2889   l2_file->u.win.curfdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
2890   memset(&l2_file->u.win.curfdr, 0, sizeof(l2_file->u.win.curfdr));
2891   memcpy(l2_file->u.win.curfdr.name, filename, 10);
2892
2893   return 0;
2894}
2895
2896/*
2897   Allocate a new (empty) file
2898*/
2899static int new_file_lvl2_tifiles(imgtool_stream *file_handle, ti99_lvl2_fileref *l2_file)
2900{
2901   /* set up file handle */
2902   l2_file->type = L2F_TIFILES;
2903   l2_file->u.tifiles.file_handle = file_handle;
2904   memset(&l2_file->u.tifiles.hdr, 0, sizeof(l2_file->u.tifiles.hdr));
2905   l2_file->u.tifiles.hdr.tifiles[0] = '\7';
2906   l2_file->u.tifiles.hdr.tifiles[1] = 'T';
2907   l2_file->u.tifiles.hdr.tifiles[2] = 'I';
2908   l2_file->u.tifiles.hdr.tifiles[3] = 'F';
2909   l2_file->u.tifiles.hdr.tifiles[4] = 'I';
2910   l2_file->u.tifiles.hdr.tifiles[5] = 'L';
2911   l2_file->u.tifiles.hdr.tifiles[6] = 'E';
2912   l2_file->u.tifiles.hdr.tifiles[7] = 'S';
2913
2914   return 0;
2915}
2916
2917/*
2918   Open an existing file on a floppy image
2919
2920   l2_img: level 2 image the file is located on
2921   fpath: access path to the file
2922   file: set up if open is successful
2923*/
2924static int open_file_lvl2_dsk(ti99_lvl2_imgref *l2_img, const char *fpath, ti99_lvl2_fileref *l2_file)
2925{
2926   int parent_ref, is_dir, catalog_index;
2927   int reply;
2928
2929
2930   reply = dsk_find_catalog_entry(l2_img, fpath, NULL, &parent_ref, &is_dir, &catalog_index);
2931   if (reply)
2932      return reply;
2933
2934   if (is_dir)
2935      /* this is not a file */
2936      return IMGTOOLERR_BADFILENAME;
2937
2938   l2_file->type = L2F_DSK;
2939   l2_file->u.dsk.l2_img = l2_img;
2940   l2_file->u.dsk.fdr_aphysrec = l2_img->u.dsk.catalogs[parent_ref].files[catalog_index].fdr_ptr;
2941   if (read_absolute_physrec(& l2_img->l1_img, l2_file->u.dsk.fdr_aphysrec, &l2_file->u.dsk.fdr))
2942      return IMGTOOLERR_READERROR;
2943
2944   return 0;
2945}
2946
2947/*
2948   Open an existing file on a harddisk image
2949
2950   l2_img: level 2 image the file is located on
2951   fpath: access path to the file
2952   file: set up if open is successful
2953*/
2954static int open_file_lvl2_win(ti99_lvl2_imgref *l2_img, const char *fpath, ti99_lvl2_fileref *l2_file)
2955{
2956   int parent_ref, is_dir, catalog_index;
2957   ti99_catalog catalog;
2958   int reply;
2959
2960   reply = win_find_catalog_entry(l2_img, fpath, NULL, &parent_ref, &catalog, &is_dir, &catalog_index);
2961   if (reply)
2962      return reply;
2963
2964   if (is_dir)
2965      /* this is not a file */
2966      return IMGTOOLERR_BADFILENAME;
2967
2968   l2_file->type = L2F_WIN;
2969   l2_file->u.win.l2_img = l2_img;
2970   l2_file->u.win.eldestfdr_aphysrec = catalog.files[catalog_index].fdr_ptr * l2_img->AUformat.physrecsperAU;
2971   l2_file->u.win.curfdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
2972   if (read_absolute_physrec(& l2_img->l1_img, l2_file->u.win.curfdr_aphysrec, &l2_file->u.win.curfdr))
2973      return IMGTOOLERR_READERROR;
2974   l2_file->u.win.fphysrecs = get_win_fdr_fphysrecs(&l2_file->u.win.curfdr);
2975
2976   /* check integrity of FDR sibling chain */
2977   /* note that as we check that the back chain is consistent with the forward
2978   chain, we will also detect any cycle in the sibling chain, so we do not
2979   need to check against them explicitely */
2980   if (get_UINT16BE(l2_file->u.win.curfdr.prevsibFDR_AU) != 0)
2981      return IMGTOOLERR_CORRUPTIMAGE;
2982
2983   {
2984      int i, pastendoflist_flag;
2985      unsigned cur_fphysrec, sibFDR_AUlen;
2986      win_fdr *cur_fdr, fdr_buf;
2987      unsigned curfdr_aphysrec, prevfdr_aphysrec;
2988
2989      cur_fphysrec = 0;
2990      pastendoflist_flag = 0;
2991      cur_fdr = &l2_file->u.win.curfdr;
2992      curfdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
2993
2994      while (1)
2995      {
2996         sibFDR_AUlen = 0;
2997         i=0;
2998         if (! pastendoflist_flag)
2999         {
3000            /* compute number of allocated AUs and check number of AUs */
3001            for (; i<54; i++)
3002            {
3003               if (get_UINT16BE(cur_fdr->clusters[i][0]) == 0)
3004               {
3005                  pastendoflist_flag = TRUE;
3006                  break;
3007               }
3008               sibFDR_AUlen += get_UINT16BE(cur_fdr->clusters[i][1])
3009                           - get_UINT16BE(cur_fdr->clusters[i][0])
3010                           + 1;
3011            }
3012         }
3013         /* clear remainder of cluster table */
3014         for (; i<54; i++)
3015         {
3016            /*set_UINT16BE(&cur_fdr->clusters[i][0], 0);
3017            set_UINT16BE(&cur_fdr->clusters[i][1], 0);*/
3018            if ((get_UINT16BE(cur_fdr->clusters[i][0]) != 0) || (get_UINT16BE(cur_fdr->clusters[i][1]) != 0))
3019               return IMGTOOLERR_CORRUPTIMAGE;
3020         }
3021
3022         /* check sibFDR_AUlen field */
3023         if (get_UINT16BE(cur_fdr->sibFDR_AUlen) != sibFDR_AUlen)
3024            return IMGTOOLERR_CORRUPTIMAGE;
3025
3026         /* update current file physrec position to point to end of sibling FDR */
3027         cur_fphysrec += sibFDR_AUlen * l2_file->u.win.l2_img->AUformat.physrecsperAU;
3028
3029         /* exit loop if end of sibling chain */
3030         if (! get_UINT16BE(cur_fdr->nextsibFDR_AU))
3031            break;
3032
3033         /* otherwise read next FDR */
3034         if (get_UINT16BE(cur_fdr->nextsibFDR_AU) >= l2_file->u.win.l2_img->AUformat.totAUs)
3035            return IMGTOOLERR_CORRUPTIMAGE;
3036
3037         prevfdr_aphysrec = curfdr_aphysrec;
3038         curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(l2_file->u.win.l2_img, cur_fdr);
3039         if (read_absolute_physrec(& l2_file->u.win.l2_img->l1_img, curfdr_aphysrec, &fdr_buf))
3040            return IMGTOOLERR_READERROR;
3041         cur_fdr = &fdr_buf;
3042
3043         /* check that back chaining is consistent with forward chaining */
3044         if (get_win_fdr_prevsibFDR_aphysrec(l2_file->u.win.l2_img, &fdr_buf) != prevfdr_aphysrec)
3045            return IMGTOOLERR_CORRUPTIMAGE;
3046         /*  check fphysrecs field */
3047         if (get_win_fdr_fphysrecs(&fdr_buf) != cur_fphysrec)
3048            return IMGTOOLERR_CORRUPTIMAGE;
3049
3050         /* check consistency of informative fields (name, record format, flags, etc) */
3051         if (memcmp(fdr_buf.name, l2_file->u.win.curfdr.name, 10)
3052               || (get_UINT16BE(fdr_buf.xreclen) != get_UINT16BE(l2_file->u.win.curfdr.xreclen))
3053               || (fdr_buf.flags != l2_file->u.win.curfdr.flags)
3054               || (fdr_buf.recsperphysrec != l2_file->u.win.curfdr.recsperphysrec)
3055               || (fdr_buf.eof != l2_file->u.win.curfdr.eof)
3056               || (fdr_buf.reclen != l2_file->u.win.curfdr.reclen)
3057               || (get_UINT16LE(fdr_buf.fixrecs_LSW) != get_UINT16LE(l2_file->u.win.curfdr.fixrecs_LSW))
3058               || memcmp(&fdr_buf.creation, &l2_file->u.win.curfdr.creation, 4)
3059               || memcmp(&fdr_buf.update, &l2_file->u.win.curfdr.update, 4)
3060               /*|| memcmp(fdr_buf.id, l2_file->u.win.curfdr.id, 2)*/
3061               || (get_UINT16BE(fdr_buf.parent_FDIR_AU) != get_UINT16BE(l2_file->u.win.curfdr.parent_FDIR_AU))
3062               || ((fdr_buf.xinfo_MSB & 0xf) != (l2_file->u.win.curfdr.xinfo_MSB & 0xf)))
3063            return IMGTOOLERR_CORRUPTIMAGE;
3064      }
3065      if (cur_fphysrec < l2_file->u.win.fphysrecs)
3066         return IMGTOOLERR_CORRUPTIMAGE;
3067   }
3068
3069   return 0;
3070}
3071
3072/*
3073   Open an existing file in TIFILES format
3074*/
3075static int open_file_lvl2_tifiles(imgtool_stream *file_handle, ti99_lvl2_fileref *l2_file)
3076{
3077   /* set up file handle */
3078   l2_file->type = L2F_TIFILES;
3079   l2_file->u.tifiles.file_handle = file_handle;
3080
3081   /* seek to header */
3082   if (stream_seek(l2_file->u.tifiles.file_handle, 0, SEEK_SET))
3083      return IMGTOOLERR_READERROR;
3084   /* read it */
3085   if (stream_read(l2_file->u.tifiles.file_handle, &l2_file->u.tifiles.hdr, sizeof(l2_file->u.tifiles.hdr)) != sizeof(l2_file->u.tifiles.hdr))
3086      return IMGTOOLERR_READERROR;
3087
3088   return 0;
3089}
3090
3091/*
3092   compute the aphysrec address for a given file physical record (fphysrec)
3093
3094   l2_img: image where the file is located
3095*/
3096static int dsk_fphysrec_to_aphysrec(ti99_lvl2_fileref_dsk *dsk_file, unsigned fphysrec, unsigned *aphysrec)
3097{
3098   int cluster_index;
3099   int cluster_firstfphysrec, cluster_lastfphysrec;
3100   int cluster_baseaphysrec;
3101
3102
3103   /* check parameter */
3104   if (fphysrec >= get_UINT16BE(dsk_file->fdr.fphysrecs))
3105      return IMGTOOLERR_UNEXPECTED;
3106
3107
3108   /* search for the cluster in the data chain pointers array */
3109   cluster_firstfphysrec = 0;
3110   for (cluster_index=0; cluster_index<76; cluster_index++)
3111   {
3112      /* read curent file block table entry */
3113      cluster_lastfphysrec = get_dsk_fdr_cluster_lastfphysrec(&dsk_file->fdr, cluster_index);
3114      if (cluster_lastfphysrec >= fphysrec)
3115         break;
3116      cluster_firstfphysrec = cluster_lastfphysrec+1;
3117   }
3118   if (cluster_index == 76)
3119      /* if not found, the file is corrupt */
3120      return IMGTOOLERR_CORRUPTIMAGE;
3121
3122   /* read base aphysrec address for this cluster */
3123   cluster_baseaphysrec = get_dsk_fdr_cluster_baseaphysrec(dsk_file->l2_img, &dsk_file->fdr, cluster_index);
3124   /* return absolute physrec address */
3125   *aphysrec = cluster_baseaphysrec + (fphysrec - cluster_firstfphysrec);
3126   return 0;
3127}
3128
3129/*
3130   compute the aphysrec address for a given file physical record (fphysrec)
3131
3132   l2_img: image where the file is located
3133*/
3134static int win_fphysrec_to_aphysrec(ti99_lvl2_fileref_win *win_file, unsigned fphysrec, unsigned *aphysrec)
3135{
3136   int cluster_index;
3137   int cluster_firstfphysrec, cluster_lastfphysrec;
3138   int cluster_baseaphysrec;
3139   int errorcode;
3140
3141
3142   /* check parameter */
3143   if (fphysrec >= win_file->fphysrecs)
3144      return IMGTOOLERR_UNEXPECTED;
3145
3146   /* look for correct sibling */
3147   if (fphysrec < get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr))
3148   {
3149      while (fphysrec < get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr))
3150      {
3151         if (get_UINT16BE(win_file->curfdr.prevsibFDR_AU) == 0)
3152            return IMGTOOLERR_CORRUPTIMAGE;
3153         errorcode = win_goto_prev_sibFDR(win_file);
3154         if (errorcode)
3155            return errorcode;
3156      }
3157   }
3158   else /*if (fphysrec >= get_win_fdr_cursibFDR_basefphysrec(& dsk_file->curfdr))*/
3159   {
3160      while (fphysrec >= (get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr)
3161                        + get_UINT16BE(win_file->curfdr.sibFDR_AUlen) * win_file->l2_img->AUformat.physrecsperAU))
3162      {
3163         if (get_UINT16BE(win_file->curfdr.nextsibFDR_AU) == 0)
3164            return IMGTOOLERR_CORRUPTIMAGE;
3165         errorcode = win_goto_next_sibFDR(win_file);
3166         if (errorcode)
3167            return errorcode;
3168      }
3169   }
3170
3171
3172   /* search for the cluster in the data chain pointers array */
3173   cluster_firstfphysrec = get_win_fdr_cursibFDR_basefphysrec(& win_file->curfdr);
3174   for (cluster_index = 0; cluster_index<54; cluster_index++)
3175   {
3176      cluster_lastfphysrec = cluster_firstfphysrec
3177                           + (get_UINT16BE(win_file->curfdr.clusters[cluster_index][1])
3178                                 - get_UINT16BE(win_file->curfdr.clusters[cluster_index][0])
3179                                 + 1)
3180                              * win_file->l2_img->AUformat.physrecsperAU;
3181      if (fphysrec < cluster_lastfphysrec)
3182         break;
3183
3184      cluster_firstfphysrec = cluster_lastfphysrec;
3185   }
3186
3187   if (cluster_index == 54)
3188      return IMGTOOLERR_CORRUPTIMAGE;
3189
3190
3191   /* read base aphysrec address for this cluster */
3192   cluster_baseaphysrec = get_UINT16BE(win_file->curfdr.clusters[cluster_index][0]) * win_file->l2_img->AUformat.physrecsperAU;
3193   /* return absolute physrec address */
3194   *aphysrec = cluster_baseaphysrec + (fphysrec - cluster_firstfphysrec);
3195   return 0;
3196}
3197
3198/*
3199   read a 256-byte physical record from a file
3200*/
3201static int read_file_physrec(ti99_lvl2_fileref *l2_file, unsigned fphysrec, void *dest)
3202{
3203   int errorcode;
3204   unsigned aphysrec;
3205
3206   switch (l2_file->type)
3207   {
3208   case L2F_DSK:
3209      /* compute absolute physrec address */
3210      errorcode = dsk_fphysrec_to_aphysrec(&l2_file->u.dsk, fphysrec, &aphysrec);
3211      if (errorcode)
3212         return errorcode;
3213      /* read physrec */
3214      if (read_absolute_physrec(& l2_file->u.dsk.l2_img->l1_img, aphysrec, dest))
3215         return IMGTOOLERR_READERROR;
3216      break;
3217
3218   case L2F_WIN:
3219      /* compute absolute physrec address */
3220      errorcode = win_fphysrec_to_aphysrec(&l2_file->u.win, fphysrec, &aphysrec);
3221      if (errorcode)
3222         return errorcode;
3223      /* read physrec */
3224      if (read_absolute_physrec(& l2_file->u.win.l2_img->l1_img, aphysrec, dest))
3225         return IMGTOOLERR_READERROR;
3226      break;
3227
3228   case L2F_TIFILES:
3229      /* seek to physrec */
3230      if (stream_seek(l2_file->u.tifiles.file_handle, 128+256*fphysrec, SEEK_SET))
3231         return IMGTOOLERR_READERROR;
3232      /* read it */
3233      if (stream_read(l2_file->u.tifiles.file_handle, dest, 256) != 256)
3234         return IMGTOOLERR_READERROR;
3235      break;
3236   }
3237
3238   return 0;
3239}
3240
3241/*
3242   read a 256-byte physical record from a file
3243*/
3244static int write_file_physrec(ti99_lvl2_fileref *l2_file, unsigned fphysrec, const void *src)
3245{
3246   int errorcode;
3247   unsigned aphysrec;
3248
3249   switch (l2_file->type)
3250   {
3251   case L2F_DSK:
3252      /* compute absolute physrec address */
3253      errorcode = dsk_fphysrec_to_aphysrec(&l2_file->u.dsk, fphysrec, &aphysrec);
3254      if (errorcode)
3255         return errorcode;
3256      /* write physrec */
3257      if (write_absolute_physrec(& l2_file->u.dsk.l2_img->l1_img, aphysrec, src))
3258         return IMGTOOLERR_WRITEERROR;
3259      break;
3260
3261   case L2F_WIN:
3262      /* compute absolute physrec address */
3263      errorcode = win_fphysrec_to_aphysrec(&l2_file->u.win, fphysrec, &aphysrec);
3264      if (errorcode)
3265         return errorcode;
3266      /* write physrec */
3267      if (write_absolute_physrec(& l2_file->u.win.l2_img->l1_img, aphysrec, src))
3268         return IMGTOOLERR_WRITEERROR;
3269      break;
3270
3271   case L2F_TIFILES:
3272      /* seek to physrec */
3273      if (stream_seek(l2_file->u.tifiles.file_handle, 128+256*fphysrec, SEEK_SET))
3274         return IMGTOOLERR_WRITEERROR;
3275      /* write it */
3276      if (stream_write(l2_file->u.tifiles.file_handle, src, 256) != 256)
3277         return IMGTOOLERR_WRITEERROR;
3278      break;
3279   }
3280
3281   return 0;
3282}
3283
3284/*
3285   Write a field in every fdr record associated to a file
3286*/
3287/*static int set_win_fdr_field(ti99_lvl2_fileref *l2_file, size_t offset, size_t size, void *data)
3288{
3289   win_fdr fdr_buf;
3290   unsigned fdr_aphysrec;
3291   int errorcode = 0;
3292
3293   for (fdr_aphysrec = l2_file->u.win.eldestfdr_aphysrec;
3294         fdr_aphysrec && ((errorcode = (read_absolute_physrec(&l2_file->u.win.l2_img->l1_img, fdr_aphysrec, &fdr_buf) ? IMGTOOLERR_READERROR : 0)) == 0);
3295         fdr_aphysrec = get_win_fdr_nextsibFDR_physrec(l2_file->u.win.l2_img, &fdr_buf))
3296   {
3297      memcpy(((UINT8 *) &fdr_buf) + offset, data, size);
3298      if (write_absolute_physrec(&l2_file->u.win.l2_img->l1_img, fdr_aphysrec, &fdr_buf))
3299      {
3300         errorcode = IMGTOOLERR_WRITEERROR;
3301         break;
3302      }
3303   }
3304
3305   return errorcode;
3306}*/
3307
3308static UINT8 get_file_flags(ti99_lvl2_fileref *l2_file)
3309{
3310   int reply = 0;
3311
3312   switch (l2_file->type)
3313   {
3314   case L2F_DSK:
3315      reply = l2_file->u.dsk.fdr.flags;
3316      break;
3317
3318   case L2F_WIN:
3319      reply = l2_file->u.win.curfdr.flags;
3320      break;
3321
3322   case L2F_TIFILES:
3323      reply = l2_file->u.tifiles.hdr.flags;
3324      break;
3325   }
3326
3327   return reply;
3328}
3329
3330static void set_file_flags(ti99_lvl2_fileref *l2_file, UINT8 data)
3331{
3332   switch (l2_file->type)
3333   {
3334   case L2F_DSK:
3335      l2_file->u.dsk.fdr.flags = data;
3336      break;
3337
3338   case L2F_WIN:
3339      l2_file->u.win.curfdr.flags = data;
3340      break;
3341
3342   case L2F_TIFILES:
3343      l2_file->u.tifiles.hdr.flags = data;
3344      break;
3345   }
3346}
3347
3348static UINT8 get_file_recsperphysrec(ti99_lvl2_fileref *l2_file)
3349{
3350   int reply = 0;
3351
3352   switch (l2_file->type)
3353   {
3354   case L2F_DSK:
3355      reply = l2_file->u.dsk.fdr.recsperphysrec;
3356      break;
3357
3358   case L2F_WIN:
3359      reply = l2_file->u.win.curfdr.recsperphysrec;
3360      break;
3361
3362   case L2F_TIFILES:
3363      reply = l2_file->u.tifiles.hdr.recsperphysrec;
3364      break;
3365   }
3366
3367   return reply;
3368}
3369
3370static void set_file_recsperphysrec(ti99_lvl2_fileref *l2_file, UINT8 data)
3371{
3372   switch (l2_file->type)
3373   {
3374   case L2F_DSK:
3375      l2_file->u.dsk.fdr.recsperphysrec = data;
3376      break;
3377
3378   case L2F_WIN:
3379      l2_file->u.win.curfdr.recsperphysrec = data;
3380      break;
3381
3382   case L2F_TIFILES:
3383      l2_file->u.tifiles.hdr.recsperphysrec = data;
3384      break;
3385   }
3386}
3387
3388static unsigned get_file_fphysrecs(ti99_lvl2_fileref *l2_file)
3389{
3390   int reply = 0;
3391
3392   switch (l2_file->type)
3393   {
3394   case L2F_DSK:
3395      reply = get_UINT16BE(l2_file->u.dsk.fdr.fphysrecs);
3396      break;
3397
3398   case L2F_WIN:
3399      reply = l2_file->u.win.fphysrecs;
3400      break;
3401
3402   case L2F_TIFILES:
3403      reply = get_UINT16BE(l2_file->u.tifiles.hdr.fphysrecs);
3404      break;
3405   }
3406
3407   return reply;
3408}
3409
3410static int set_file_fphysrecs(ti99_lvl2_fileref *l2_file, unsigned data)
3411{
3412   switch (l2_file->type)
3413   {
3414   case L2F_DSK:
3415      if (data >= 65536)
3416         return IMGTOOLERR_UNIMPLEMENTED;
3417      set_UINT16BE(&l2_file->u.dsk.fdr.fphysrecs, data);
3418      break;
3419
3420   case L2F_WIN:
3421      l2_file->u.win.fphysrecs = data;
3422      break;
3423
3424   case L2F_TIFILES:
3425      if (data >= 65536)
3426         return IMGTOOLERR_UNIMPLEMENTED;
3427      set_UINT16BE(&l2_file->u.tifiles.hdr.fphysrecs, data);
3428      break;
3429   }
3430
3431   return 0;
3432}
3433
3434static UINT8 get_file_eof(ti99_lvl2_fileref *l2_file)
3435{
3436   int reply = 0;
3437
3438   switch (l2_file->type)
3439   {
3440   case L2F_DSK:
3441      reply = l2_file->u.dsk.fdr.eof;
3442      break;
3443
3444   case L2F_WIN:
3445      reply = l2_file->u.win.curfdr.eof;
3446      break;
3447
3448   case L2F_TIFILES:
3449      reply = l2_file->u.tifiles.hdr.eof;
3450      break;
3451   }
3452
3453   return reply;
3454}
3455
3456static void set_file_eof(ti99_lvl2_fileref *l2_file, UINT8 data)
3457{
3458   switch (l2_file->type)
3459   {
3460   case L2F_DSK:
3461      l2_file->u.dsk.fdr.eof = data;
3462      break;
3463
3464   case L2F_WIN:
3465      l2_file->u.win.curfdr.eof = data;
3466      break;
3467
3468   case L2F_TIFILES:
3469      l2_file->u.tifiles.hdr.eof = data;
3470      break;
3471   }
3472}
3473
3474static UINT16 get_file_reclen(ti99_lvl2_fileref *l2_file)
3475{
3476   int reply = 0;
3477
3478   switch (l2_file->type)
3479   {
3480   case L2F_DSK:
3481      reply = l2_file->u.dsk.fdr.reclen;
3482      if ((reply == 0) && (! (l2_file->u.dsk.fdr.flags & (fdr99_f_program /*| fdr99_f_var*/))))
3483         reply = get_UINT16BE(l2_file->u.dsk.fdr.xreclen);
3484      break;
3485
3486   case L2F_WIN:
3487      reply = l2_file->u.win.curfdr.reclen;
3488      if ((reply == 0) && (! (l2_file->u.win.curfdr.flags & (fdr99_f_program /*| fdr99_f_var*/))))
3489         reply = get_UINT16BE(l2_file->u.win.curfdr.xreclen);
3490      break;
3491
3492   case L2F_TIFILES:
3493      reply = l2_file->u.tifiles.hdr.reclen;
3494      break;
3495   }
3496
3497   return reply;
3498}
3499
3500static int set_file_reclen(ti99_lvl2_fileref *l2_file, UINT16 data)
3501{
3502   switch (l2_file->type)
3503   {
3504   case L2F_DSK:
3505      if (data < 256)
3506      {
3507         l2_file->u.dsk.fdr.reclen = data;
3508         set_UINT16BE(&l2_file->u.dsk.fdr.xreclen, 0);
3509      }
3510      else
3511      {
3512         l2_file->u.dsk.fdr.reclen = 0;
3513         set_UINT16BE(&l2_file->u.dsk.fdr.xreclen, data);
3514      }
3515      break;
3516
3517   case L2F_WIN:
3518      if (data < 256)
3519      {
3520         l2_file->u.win.curfdr.reclen = data;
3521         set_UINT16BE(&l2_file->u.win.curfdr.xreclen, 0);
3522      }
3523      else
3524      {
3525         l2_file->u.win.curfdr.reclen = 0;
3526         set_UINT16BE(&l2_file->u.win.curfdr.xreclen, data);
3527      }
3528      break;
3529
3530   case L2F_TIFILES:
3531      if (data >= 256)
3532         return IMGTOOLERR_UNIMPLEMENTED;
3533      l2_file->u.tifiles.hdr.reclen = data;
3534      break;
3535   }
3536
3537   return 0;
3538}
3539
3540static unsigned get_file_fixrecs(ti99_lvl2_fileref *l2_file)
3541{
3542   int reply = 0;
3543
3544   switch (l2_file->type)
3545   {
3546   case L2F_DSK:
3547      reply = get_UINT16LE(l2_file->u.dsk.fdr.fixrecs);
3548      break;
3549
3550   case L2F_WIN:
3551      reply = get_win_fdr_fixrecs(&l2_file->u.win.curfdr);
3552      break;
3553
3554   case L2F_TIFILES:
3555      reply = get_UINT16BE(l2_file->u.tifiles.hdr.fixrecs);
3556      break;
3557   }
3558
3559   return reply;
3560}
3561
3562static int set_file_fixrecs(ti99_lvl2_fileref *l2_file, unsigned data)
3563{
3564   switch (l2_file->type)
3565   {
3566   case L2F_DSK:
3567      if (data >= 65536)
3568         return IMGTOOLERR_UNIMPLEMENTED;
3569      set_UINT16LE(&l2_file->u.dsk.fdr.fixrecs, data);
3570      break;
3571
3572   case L2F_WIN:
3573      set_win_fdr_fixrecs(&l2_file->u.win.curfdr, data);
3574      break;
3575
3576   case L2F_TIFILES:
3577      if (data >= 65536)
3578         return IMGTOOLERR_UNIMPLEMENTED;
3579      set_UINT16BE(&l2_file->u.tifiles.hdr.fixrecs, data);
3580      break;
3581   }
3582
3583   return 0;
3584}
3585
3586static void get_file_creation_date(ti99_lvl2_fileref *l2_file, ti99_date_time *reply)
3587{
3588   switch (l2_file->type)
3589   {
3590   case L2F_DSK:
3591      *reply = l2_file->u.dsk.fdr.creation;
3592      break;
3593
3594   case L2F_WIN:
3595      *reply = l2_file->u.win.curfdr.creation;
3596      break;
3597
3598   case L2F_TIFILES:
3599      memset(reply, 0, sizeof(*reply));
3600      break;
3601   }
3602}
3603
3604static void set_file_creation_date(ti99_lvl2_fileref *l2_file, ti99_date_time data)
3605{
3606   switch (l2_file->type)
3607   {
3608   case L2F_DSK:
3609      l2_file->u.dsk.fdr.creation = data;
3610      break;
3611
3612   case L2F_WIN:
3613      l2_file->u.win.curfdr.creation = data;
3614      break;
3615
3616   case L2F_TIFILES:
3617      break;
3618   }
3619}
3620
3621static void get_file_update_date(ti99_lvl2_fileref *l2_file, ti99_date_time *reply)
3622{
3623   switch (l2_file->type)
3624   {
3625   case L2F_DSK:
3626      *reply = l2_file->u.dsk.fdr.update;
3627      break;
3628
3629   case L2F_WIN:
3630      *reply = l2_file->u.win.curfdr.update;
3631      break;
3632
3633   case L2F_TIFILES:
3634      memset(reply, 0, sizeof(*reply));
3635      break;
3636   }
3637}
3638
3639static void set_file_update_date(ti99_lvl2_fileref *l2_file, ti99_date_time data)
3640{
3641   switch (l2_file->type)
3642   {
3643   case L2F_DSK:
3644      l2_file->u.dsk.fdr.update = data;
3645      break;
3646
3647   case L2F_WIN:
3648      l2_file->u.win.curfdr.update = data;
3649      break;
3650
3651   case L2F_TIFILES:
3652      break;
3653   }
3654}
3655
3656#ifdef UNUSED_FUNCTION
3657static void current_date_time(ti99_date_time *reply)
3658{
3659   /* All these functions should be ANSI */
3660   time_t cur_time = time(NULL);
3661   struct tm expanded_time = *localtime(& cur_time);
3662
3663   reply->time_MSB = (expanded_time.tm_hour << 3) | (expanded_time.tm_min >> 3);
3664   reply->time_LSB = (expanded_time.tm_min << 5) | (expanded_time.tm_sec >> 1);
3665   reply->date_MSB = ((expanded_time.tm_year % 100) << 1) | ((expanded_time.tm_mon+1) >> 3);
3666   reply->date_LSB = ((expanded_time.tm_mon+1) << 5) | expanded_time.tm_mday;
3667}
3668#endif
3669
3670#if 0
3671#pragma mark -
3672#pragma mark LEVEL 3 DISK ROUTINES
3673#endif
3674
3675/*
3676   Level 3 implements files as a succession of logical records.
3677
3678   There are three types of files:
3679   * program files that are not implemented at level 3 (no logical record)
3680   * files with fixed-size records (random-access files)
3681   * files with variable-size records (sequential-access)
3682*/
3683
3684typedef struct ti99_lvl3_fileref
3685{
3686   ti99_lvl2_fileref l2_file;
3687
3688   int cur_log_rec;
3689   int cur_phys_rec;
3690   int cur_pos_in_phys_rec;
3691} ti99_lvl3_fileref;
3692
3693#ifdef UNUSED_FUNCTION
3694/*
3695   Open a file on level 3.
3696
3697   To open a file on level 3, you must open (or create) the file on level 2,
3698   then pass the file reference to open_file_lvl3.
3699*/
3700static int open_file_lvl3(ti99_lvl3_fileref *l3_file)
3701{
3702   l3_file->cur_log_rec = 0;
3703   l3_file->cur_phys_rec = 0;
3704   l3_file->cur_pos_in_phys_rec = 0;
3705
3706   /*if ()*/
3707
3708   return 0;
3709}
3710
3711/*
3712   Test a file for EOF
3713*/
3714static int is_eof(ti99_lvl3_fileref *l3_file)
3715{
3716   int flags = get_file_flags(&l3_file->l2_file);
3717   int fphysrecs = get_file_fphysrecs(&l3_file->l2_file);
3718   int fdr_eof = get_file_eof(&l3_file->l2_file);
3719
3720   if (flags & fdr99_f_var)
3721   {
3722      return (l3_file->cur_phys_rec >= fphysrecs);
3723   }
3724   else
3725   {
3726      return ((l3_file->cur_phys_rec >= fphysrecs)
3727            || ((l3_file->cur_phys_rec == (fphysrecs-1))
3728               && (l3_file->cur_pos_in_phys_rec >= (fdr_eof ? fdr_eof : 256))));
3729   }
3730}
3731
3732/*
3733   Read next record from a file
3734*/
3735static int read_next_record(ti99_lvl3_fileref *l3_file, void *dest, int *out_reclen)
3736{
3737   int errorcode;
3738   UINT8 physrec_buf[256];
3739   int reclen;
3740   int flags = get_file_flags(&l3_file->l2_file);
3741   int fphysrecs = get_file_fphysrecs(&l3_file->l2_file);
3742   int fdr_eof = get_file_eof(&l3_file->l2_file);
3743
3744   if (flags & fdr99_f_program)
3745   {
3746      /* program files have no level-3 record */
3747      return IMGTOOLERR_UNEXPECTED;
3748   }
3749   else if (flags & fdr99_f_var)
3750   {
3751      /* variable-lenght records */
3752      if (is_eof(l3_file))
3753         return IMGTOOLERR_UNEXPECTED;
3754      errorcode = read_file_physrec(&l3_file->l2_file, l3_file->cur_phys_rec, physrec_buf);
3755      if (errorcode)
3756         return errorcode;
3757      /* read reclen */
3758      reclen = physrec_buf[l3_file->cur_pos_in_phys_rec];
3759      /* check integrity */
3760      if ((reclen == 0xff) || (reclen > get_file_reclen(&l3_file->l2_file))
3761            || ((l3_file->cur_pos_in_phys_rec + 1 + reclen) > 256))
3762         return IMGTOOLERR_CORRUPTIMAGE;
3763      /* copy to buffer */
3764      memcpy(dest, physrec_buf + l3_file->cur_pos_in_phys_rec + 1, reclen);
3765      l3_file->cur_pos_in_phys_rec += reclen + 1;
3766      /* skip to next physrec if needed */
3767      if ((l3_file->cur_pos_in_phys_rec == 256)
3768            || (physrec_buf[l3_file->cur_pos_in_phys_rec] == 0xff))
3769      {
3770         l3_file->cur_pos_in_phys_rec = 0;
3771         l3_file->cur_phys_rec++;
3772      }
3773      (* out_reclen) = reclen;
3774   }
3775   else
3776   {
3777      /* fixed len records */
3778      reclen = get_file_reclen(&l3_file->l2_file);
3779      if (is_eof(l3_file))
3780         return IMGTOOLERR_UNEXPECTED;
3781      if ((l3_file->cur_pos_in_phys_rec + reclen) > 256)
3782      {
3783         l3_file->cur_pos_in_phys_rec = 0;
3784         l3_file->cur_phys_rec++;
3785      }
3786      if ((l3_file->cur_phys_rec >= fphysrecs)
3787            || ((l3_file->cur_phys_rec == (fphysrecs-1))
3788               && ((l3_file->cur_pos_in_phys_rec + reclen) >= (fdr_eof ? fdr_eof : 256))))
3789         return IMGTOOLERR_CORRUPTIMAGE;
3790      errorcode = read_file_physrec(&l3_file->l2_file, l3_file->cur_phys_rec, physrec_buf);
3791      if (errorcode)
3792         return errorcode;
3793      memcpy(dest, physrec_buf + l3_file->cur_pos_in_phys_rec, reclen);
3794      l3_file->cur_pos_in_phys_rec += reclen;
3795      if (l3_file->cur_pos_in_phys_rec == 256)
3796      {
3797         l3_file->cur_pos_in_phys_rec = 0;
3798         l3_file->cur_phys_rec++;
3799      }
3800      (* out_reclen) = reclen;
3801   }
3802
3803   return 0;
3804}
3805#endif
3806
3807#if 0
3808#pragma mark -
3809#pragma mark IMGTOOL MODULE IMPLEMENTATION
3810#endif
3811
3812/*
3813   ti99 catalog iterator, used when imgtool reads the catalog
3814*/
3815typedef struct dsk_iterator
3816{
3817   ti99_lvl2_imgref *image;
3818   int level;
3819   int listing_subdirs;      /* true if we are listing subdirectories at current level */
3820   int index[2];            /* current index in the disk catalog */
3821   ti99_catalog *cur_catalog;   /* current catalog */
3822} dsk_iterator;
3823
3824typedef struct win_iterator
3825{
3826   ti99_lvl2_imgref *image;
3827   int level;
3828   int listing_subdirs;      /* true if we are listing subdirectories at current level */
3829   int index[MAX_DIR_LEVEL];   /* current index in the disk catalog */
3830   ti99_catalog catalog[MAX_DIR_LEVEL];   /* current catalog */
3831} win_iterator;
3832
3833
3834static imgtoolerr_t dsk_image_init_mess(imgtool_image *image, imgtool_stream *f);
3835static imgtoolerr_t dsk_image_init_v9t9(imgtool_image *image, imgtool_stream *f);
3836static imgtoolerr_t dsk_image_init_pc99_fm(imgtool_image *image, imgtool_stream *f);
3837static imgtoolerr_t dsk_image_init_pc99_mfm(imgtool_image *image, imgtool_stream *f);
3838static imgtoolerr_t win_image_init(imgtool_image *image, imgtool_stream *f);
3839static void ti99_image_exit(imgtool_image *img);
3840static void ti99_image_info(imgtool_image *img, char *string, size_t len);
3841static imgtoolerr_t dsk_image_beginenum(imgtool_directory *enumeration, const char *path);
3842static imgtoolerr_t dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
3843static imgtoolerr_t win_image_beginenum(imgtool_directory *enumeration, const char *path);
3844static imgtoolerr_t win_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
3845static imgtoolerr_t ti99_image_freespace(imgtool_partition *partition, UINT64 *size);
3846static imgtoolerr_t ti99_image_readfile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *destf);
3847static imgtoolerr_t ti99_image_writefile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions);
3848static imgtoolerr_t dsk_image_deletefile(imgtool_partition *partition, const char *fpath);
3849static imgtoolerr_t win_image_deletefile(imgtool_partition *partition, const char *fpath);
3850static imgtoolerr_t dsk_image_create_mess(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions);
3851static imgtoolerr_t dsk_image_create_v9t9(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions);
3852
3853enum
3854{
3855   dsk_createopts_volname = 'A',
3856   dsk_createopts_sides = 'B',
3857   dsk_createopts_tracks = 'C',
3858   dsk_createopts_sectors = 'D',
3859   dsk_createopts_protection = 'E',
3860   dsk_createopts_density = 'F'
3861};
3862
3863OPTION_GUIDE_START( dsk_create_optionguide )
3864   OPTION_STRING(dsk_createopts_volname, "label",   "Volume name" )
3865   OPTION_INT(dsk_createopts_sides, "sides", "Sides" )
3866   OPTION_INT(dsk_createopts_tracks, "tracks", "Tracks" )
3867   OPTION_INT(dsk_createopts_sectors, "sectors",   "Sectors (1->9 for SD, 1->18 for DD, 1->36 for HD)" )
3868   OPTION_INT(dsk_createopts_protection, "protection", "Protection (0 for normal, 1 for protected)" )
3869   OPTION_ENUM_START(dsk_createopts_density, "density", "Density" )
3870      OPTION_ENUM(   0,      "Auto",            "Auto" )
3871      OPTION_ENUM(   1,      "SD",            "Single Density" )
3872      OPTION_ENUM(   2,      "DD",            "Double Density" )
3873      OPTION_ENUM(   3,      "HD",            "High Density" )
3874   OPTION_ENUM_END
3875OPTION_GUIDE_END
3876
3877#define dsk_create_optionspecs "B1-[2];C1-[40]-80;D1-[18]-36;E[0]-1;F[0]-3"
3878
3879static void ti99_getinfo(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3880{
3881   switch(state)
3882   {
3883      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(ti99_lvl2_imgref); break;
3884      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(dsk_iterator); break;
3885
3886      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
3887      case IMGTOOLINFO_PTR_CLOSE:                     info->close = ti99_image_exit; break;
3888      case IMGTOOLINFO_PTR_INFO:                     info->info = ti99_image_info; break;
3889      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = ti99_image_freespace; break;
3890      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = ti99_image_readfile; break;
3891      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = ti99_image_writefile; break;
3892   }
3893}
3894
3895static void ti99_dsk_getinfo(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3896{
3897   switch(state)
3898   {
3899      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "dsk"); break;
3900      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = dsk_image_beginenum; break;
3901      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = dsk_image_nextenum; break;
3902      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = dsk_image_deletefile; break;
3903      default:                                 ti99_getinfo(imgclass, state, info);
3904   }
3905}
3906
3907void ti99_old_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3908{
3909   switch(state)
3910   {
3911      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "ti99_old"); break;
3912      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (old MESS format)"); break;
3913      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_mess; break;
3914      case IMGTOOLINFO_PTR_CREATE:            info->create = dsk_image_create_mess; break;
3915      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:   info->createimage_optguide = dsk_create_optionguide; break;
3916      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:   strcpy(info->s = imgtool_temp_str(), dsk_create_optionspecs); break;
3917      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3918   }
3919}
3920
3921void ti99_v9t9_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3922{
3923   switch(state)
3924   {
3925      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "v9t9"); break;
3926      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (V9T9 format)"); break;
3927      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_v9t9; break;
3928      case IMGTOOLINFO_PTR_CREATE:            info->create = dsk_image_create_v9t9; break;
3929      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:   info->createimage_optguide = dsk_create_optionguide; break;
3930      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:   strcpy(info->s = imgtool_temp_str(), dsk_create_optionspecs); break;
3931      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3932   }
3933}
3934
3935void ti99_pc99fm_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3936{
3937   switch(state)
3938   {
3939      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "pc99fm"); break;
3940      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (PC99 FM format)"); break;
3941      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_pc99_fm; break;
3942      case IMGTOOLINFO_PTR_CREATE:            /* info->create = dsk_image_create_pc99fm; */ break;
3943      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3944   }
3945}
3946
3947void ti99_pc99mfm_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3948{
3949   switch(state)
3950   {
3951      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "pc99mfm"); break;
3952      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Diskette (PC99 MFM format)"); break;
3953      case IMGTOOLINFO_PTR_OPEN:               info->open = dsk_image_init_pc99_mfm; break;
3954      case IMGTOOLINFO_PTR_CREATE:            /* info->create = dsk_image_create_pc99mfm; */ break;
3955      default:                           ti99_dsk_getinfo(imgclass, state, info); break;
3956   }
3957}
3958
3959void ti99_ti99hd_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
3960{
3961   switch(state)
3962   {
3963      case IMGTOOLINFO_STR_NAME:               strcpy(info->s = imgtool_temp_str(), "ti99hd"); break;
3964      case IMGTOOLINFO_STR_DESCRIPTION:         strcpy(info->s = imgtool_temp_str(), "TI99 Harddisk"); break;
3965      case IMGTOOLINFO_PTR_OPEN:               info->open = win_image_init; break;
3966      case IMGTOOLINFO_PTR_CREATE:            /* info->create = hd_image_create; */ break;
3967
3968      case IMGTOOLINFO_STR_FILE_EXTENSIONS:      strcpy(info->s = imgtool_temp_str(), "hd"); break;
3969      case IMGTOOLINFO_PTR_BEGIN_ENUM:         info->begin_enum = win_image_beginenum; break;
3970      case IMGTOOLINFO_PTR_NEXT_ENUM:            info->next_enum = win_image_nextenum; break;
3971      case IMGTOOLINFO_PTR_DELETE_FILE:         info->delete_file = win_image_deletefile; break;
3972      default:                           ti99_getinfo(imgclass, state, info);
3973   }
3974}
3975
3976
3977
3978/*
3979   Open a file as a ti99_image (common code).
3980*/
3981static int dsk_image_init(imgtool_image *img, imgtool_stream *f, ti99_img_format img_format)
3982{
3983   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
3984   dsk_vib vib;
3985   int reply;
3986   int totphysrecs;
3987   unsigned fdir_aphysrec;
3988   int i;
3989
3990   /* open disk image at level 1 */
3991   reply = open_image_lvl1(f, img_format, &image->l1_img, &vib);
3992   if (reply)
3993      return reply;
3994
3995   /* open disk image at level 2 */
3996   image->type = L2I_DSK;
3997
3998   /* first compute AU size and number of AUs */
3999   totphysrecs = get_UINT16BE(vib.totphysrecs);
4000
4001   image->AUformat.physrecsperAU = (totphysrecs + 1599) / 1600;
4002   /* round to next larger power of 2 */
4003   for (i = 1; i < image->AUformat.physrecsperAU; i <<= 1)
4004      ;
4005   image->AUformat.physrecsperAU = i;
4006   image->AUformat.totAUs = totphysrecs / image->AUformat.physrecsperAU;
4007
4008   /* extract number of physrecs */
4009   image->u.dsk.totphysrecs = get_UINT16BE(vib.totphysrecs);
4010
4011   /* read and check main volume catalog */
4012   reply = dsk_read_catalog(image, 1, &image->u.dsk.catalogs[0]);
4013   if (reply)
4014      return reply;
4015
4016   image->u.dsk.fdir_aphysrec[0] = 1;
4017
4018   /* read and check subdirectory catalogs */
4019   /* Note that the reserved areas used for HFDC subdirs may be used for other
4020   purposes by other FDRs, so, if we get any error, we will assume there is no
4021   subdir after all... */
4022   image->u.dsk.catalogs[0].num_subdirs = 0;
4023   for (i=0; i<3; i++)
4024   {
4025      fdir_aphysrec = get_UINT16BE(vib.subdir[i].fdir_aphysrec);
4026      if ((! memcmp(vib.subdir[i].name, "\0\0\0\0\0\0\0\0\0\0", 10))
4027            || (! memcmp(vib.subdir[i].name, "          ", 10)))
4028      {
4029         /* name is empty: fine with us unless there is a fdir pointer */
4030         if (fdir_aphysrec != 0)
4031         {
4032            image->u.dsk.catalogs[0].num_subdirs = 0;
4033            break;
4034         }
4035      }
4036      else if (check_fname(vib.subdir[i].name))
4037      {
4038         /* name is invalid: this is not an HFDC format floppy */
4039         image->u.dsk.catalogs[0].num_subdirs = 0;
4040         break;
4041      }
4042      else
4043      {
4044         /* there is a non-empty name */
4045         if ((fdir_aphysrec == 0) || (fdir_aphysrec >= totphysrecs))
4046         {
4047            /* error: fdir pointer is invalid or NULL */
4048            image->u.dsk.catalogs[0].num_subdirs = 0;
4049            break;
4050         }
4051         /* fill in descriptor fields */
4052         image->u.dsk.fdir_aphysrec[image->u.dsk.catalogs[0].num_subdirs+1] = fdir_aphysrec;
4053         /*image->u.dsk.catalogs[0].subdirs[image->u.dsk.catalogs[0].num_subdirs].dir_ptr = fdir_aphysrec;*/
4054         memcpy(image->u.dsk.catalogs[0].subdirs[image->u.dsk.catalogs[0].num_subdirs].name, vib.subdir[i].name, 10);
4055         reply = dsk_read_catalog(image, fdir_aphysrec, &image->u.dsk.catalogs[image->u.dsk.catalogs[0].num_subdirs+1]);
4056         if (reply)
4057         {
4058            /* error: invalid fdir */
4059            image->u.dsk.catalogs[0].num_subdirs = 0;
4060            break;
4061         }
4062         /* found valid subdirectory: increment subdir count */
4063         image->u.dsk.catalogs[0].num_subdirs++;
4064      }
4065   }
4066
4067   /* extract volume name */
4068   memcpy(image->vol_name, vib.name, 10);
4069
4070   /* initialize default data_offset */
4071   image->data_offset = 32+2;
4072
4073   return 0;
4074}
4075
4076/*
4077   Open a file as a ti99_image (MESS format).
4078*/
4079static imgtoolerr_t dsk_image_init_mess(imgtool_image *image, imgtool_stream *f)
4080{
4081   return dsk_image_init(image, f, if_mess);
4082}
4083
4084/*
4085   Open a file as a ti99_image (V9T9 format).
4086*/
4087static imgtoolerr_t dsk_image_init_v9t9(imgtool_image *image, imgtool_stream *f)
4088{
4089   return dsk_image_init(image, f, if_v9t9);
4090}
4091
4092/*
4093   Open a file as a ti99_image (PC99 FM format).
4094*/
4095static imgtoolerr_t dsk_image_init_pc99_fm(imgtool_image *image, imgtool_stream *f)
4096{
4097   return dsk_image_init(image, f, if_pc99_fm);
4098}
4099
4100/*
4101   Open a file as a ti99_image (PC99 MFM format).
4102*/
4103static imgtoolerr_t dsk_image_init_pc99_mfm(imgtool_image *image, imgtool_stream *f)
4104{
4105   return dsk_image_init(image, f, if_pc99_mfm);
4106}
4107
4108/*
4109   Open a file as a ti99_image (harddisk format).
4110*/
4111static imgtoolerr_t win_image_init(imgtool_image *img, imgtool_stream *f)
4112{
4113   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4114   win_vib_ddr vib;
4115   int reply;
4116   int i;
4117
4118   /* open disk image at level 1 */
4119   reply = open_image_lvl1(f, if_harddisk, & image->l1_img, NULL);
4120   if (reply)
4121      return reply;
4122
4123   /* open disk image at level 2 */
4124   image->type = L2I_WIN;
4125
4126   /* read VIB */
4127   reply = read_absolute_physrec(&image->l1_img, 0, &vib);
4128   if (reply)
4129      return reply;
4130
4131   /* guess VIB version */
4132   image->u.win.vib_version = memcmp(vib.u.vib_v1.id, "WIN", 3) ? win_vib_v2 : win_vib_v1;
4133
4134   /* extract AU size and number of AUs */
4135   image->AUformat.physrecsperAU = ((get_UINT16BE(vib.params) >> 12) & 0xf) + 1;
4136   image->AUformat.totAUs = get_UINT16BE(vib.totAUs);
4137
4138   /* extract volume name */
4139   memcpy(image->vol_name, vib.name, 10);
4140
4141   /* extract data_offset */
4142   switch (image->u.win.vib_version)
4143   {
4144   case win_vib_v1:
4145      image->data_offset = 64;
4146      break;
4147
4148   case win_vib_v2:
4149      image->data_offset = vib.u.vib_v2.res_AUs * 64;
4150      break;
4151   }
4152
4153   /* read allocation bitmap (aphysrecs 1 through n, n<=33) */
4154   for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
4155   {
4156      reply = read_absolute_physrec(&image->l1_img, i+1, image->abm+i*256);
4157      if (reply)
4158         return reply;
4159   }
4160
4161   return 0;
4162}
4163
4164/*
4165   close a ti99_image
4166*/
4167static void ti99_image_exit(imgtool_image *img)
4168{
4169   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4170
4171   close_image_lvl1(&image->l1_img);
4172}
4173
4174/*
4175   get basic information on a ti99_image
4176
4177   Currently returns the volume name
4178*/
4179static void ti99_image_info(imgtool_image *img, char *string, size_t len)
4180{
4181   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4182   char vol_name[11];
4183
4184   fname_to_str(vol_name, image->vol_name, 11);
4185
4186   snprintf(string, len, "%s", vol_name);
4187}
4188
4189/*
4190   Open the disk catalog for enumeration
4191*/
4192static imgtoolerr_t dsk_image_beginenum(imgtool_directory *enumeration, const char *path)
4193{
4194   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
4195   dsk_iterator *iter = (dsk_iterator *) imgtool_directory_extrabytes(enumeration);
4196
4197   iter->image = image;
4198   iter->level = 0;
4199   iter->listing_subdirs = 1;
4200   iter->index[0] = 0;
4201   iter->cur_catalog = &iter->image->u.dsk.catalogs[0];
4202
4203   return 0;
4204}
4205
4206/*
4207   Enumerate disk catalog next entry
4208*/
4209static imgtoolerr_t dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
4210{
4211   dsk_iterator *iter = (dsk_iterator*) imgtool_directory_extrabytes(enumeration);
4212   dsk_fdr fdr;
4213   int reply;
4214   unsigned fdr_aphysrec;
4215
4216
4217   ent->corrupt = 0;
4218   ent->eof = 0;
4219
4220   /* iterate through catalogs to next file or dir entry */
4221   while ((iter->level >= 0)
4222         && (iter->index[iter->level] >= (iter->listing_subdirs
4223                                    ? iter->cur_catalog->num_subdirs
4224                                    : iter->cur_catalog->num_files)))
4225   {
4226      if (iter->listing_subdirs)
4227      {
4228         iter->listing_subdirs = 0;
4229         iter->index[iter->level] = 0;
4230      }
4231      else
4232      {
4233         iter->listing_subdirs = 1;
4234         if (! iter->level)
4235            iter->level = -1;
4236         else
4237         {
4238            iter->level = 0;
4239            iter->index[0]++;
4240            iter->cur_catalog = &iter->image->u.dsk.catalogs[0];
4241         }
4242      }
4243   }
4244
4245   if (iter->level < 0)
4246   {
4247      ent->eof = 1;
4248   }
4249   else
4250   {
4251      if (iter->listing_subdirs)
4252      {
4253         fname_to_str(ent->filename, iter->image->u.dsk.catalogs[0].subdirs[iter->index[iter->level]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4254
4255         /* set type of DIR */
4256         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "DIR");
4257
4258         /* len in physrecs */
4259         ent->filesize = 1;
4260
4261         /* recurse subdirectory */
4262         iter->listing_subdirs = 0;   /* no need to list subdirs as only the
4263                              root dir has subdirs in DSK format */
4264         iter->level = 1;
4265         iter->cur_catalog = &iter->image->u.dsk.catalogs[iter->index[0]+1];
4266         iter->index[iter->level] = 0;
4267      }
4268      else
4269      {
4270         fdr_aphysrec = iter->cur_catalog->files[iter->index[iter->level]].fdr_ptr;
4271         reply = read_absolute_physrec(& iter->image->l1_img, fdr_aphysrec, & fdr);
4272         if (reply)
4273            return IMGTOOLERR_READERROR;
4274#if 0
4275         fname_to_str(ent->filename, fdr.name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4276#else
4277         {
4278            char buf[11];
4279
4280            ent->filename[0] = '\0';
4281            if (iter->level)
4282            {
4283               fname_to_str(ent->filename, iter->image->u.dsk.catalogs[0].subdirs[iter->index[0]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4284               strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4285            }
4286            fname_to_str(buf, fdr.name, 11);
4287            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4288         }
4289#endif
4290         /* parse flags */
4291         if (fdr.flags & fdr99_f_program)
4292            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "PGM%s",
4293                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4294         else
4295            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%c/%c %d%s",
4296                     (fdr.flags & fdr99_f_int) ? 'I' : 'D',
4297                     (fdr.flags & fdr99_f_var) ? 'V' : 'F',
4298                     fdr.reclen,
4299                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4300         /* len in physrecs */
4301         ent->filesize = get_UINT16BE(fdr.fphysrecs);
4302
4303         iter->index[iter->level]++;
4304      }
4305   }
4306
4307   return 0;
4308}
4309
4310/*
4311   Open the disk catalog for enumeration
4312*/
4313static imgtoolerr_t win_image_beginenum(imgtool_directory *enumeration, const char *path)
4314{
4315   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
4316   win_iterator *iter = (win_iterator *) imgtool_directory_extrabytes(enumeration);
4317   imgtoolerr_t errorcode;
4318
4319   iter->image = image;
4320   iter->level = 0;
4321   iter->listing_subdirs = 1;
4322   iter->index[0] = 0;
4323   errorcode = win_read_catalog(image, 0, &iter->catalog[0]);
4324   if (errorcode)
4325      return errorcode;
4326
4327   return 0;
4328}
4329
4330/*
4331   Enumerate disk catalog next entry
4332*/
4333static imgtoolerr_t win_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
4334{
4335   win_iterator *iter = (win_iterator *) imgtool_directory_extrabytes(enumeration);
4336   unsigned fdr_aphysrec;
4337   win_fdr fdr;
4338   int reply;
4339   int i;
4340
4341
4342   ent->corrupt = 0;
4343   ent->eof = 0;
4344
4345   /* iterate through catalogs to next file or dir entry */
4346   while ((iter->level >= 0)
4347         && (iter->index[iter->level] >= (iter->listing_subdirs
4348                                    ? iter->catalog[iter->level].num_subdirs
4349                                    : iter->catalog[iter->level].num_files)))
4350   {
4351      if (iter->listing_subdirs)
4352      {
4353         iter->listing_subdirs = 0;
4354         iter->index[iter->level] = 0;
4355      }
4356      else
4357      {
4358         iter->listing_subdirs = 1;
4359         iter->level--;
4360         iter->index[iter->level]++;
4361      }
4362   }
4363
4364   if (iter->level < 0)
4365   {
4366      ent->eof = 1;
4367   }
4368   else
4369   {
4370      if (iter->listing_subdirs)
4371      {
4372#if 0
4373         fname_to_str(ent->filename, iter->catalog[iter->level].subdirs[iter->index[iter->level]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4374#else
4375         {
4376            char buf[11];
4377
4378            ent->filename[0] = '\0';
4379            for (i=0; i<iter->level; i++)
4380            {
4381               fname_to_str(buf, iter->catalog[i].subdirs[iter->index[i]].name, 11);
4382               strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4383               strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4384            }
4385            fname_to_str(buf, iter->catalog[iter->level].subdirs[iter->index[iter->level]].name, 11);
4386            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4387         }
4388#endif
4389
4390         /* set type of DIR */
4391         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "DIR");
4392
4393         /* len in physrecs */
4394         ent->filesize = 2;
4395
4396         /* recurse subdirectory */
4397         /*iter->listing_subdirs = 1;*/
4398         iter->level++;
4399         iter->index[iter->level] = 0;
4400         reply = win_read_catalog(iter->image, iter->catalog[iter->level-1].subdirs[iter->index[iter->level-1]].dir_ptr, &iter->catalog[iter->level]);
4401         if (reply)
4402         {
4403            ent->corrupt = 1;
4404            return reply;
4405         }
4406      }
4407      else
4408      {
4409         fdr_aphysrec = iter->catalog[iter->level].files[iter->index[iter->level]].fdr_ptr*iter->image->AUformat.physrecsperAU;
4410         reply = read_absolute_physrec(& iter->image->l1_img, fdr_aphysrec, & fdr);
4411         if (reply)
4412            return IMGTOOLERR_READERROR;
4413#if 0
4414         fname_to_str(ent->filename, iter->catalog[iter->level].files[iter->index[iter->level]].name, sizeof(ent->filename) / sizeof(ent->filename[0]));
4415#else
4416         {
4417            char buf[11];
4418
4419            ent->filename[0] = '\0';
4420            for (i=0; i<iter->level; i++)
4421            {
4422               fname_to_str(buf, iter->catalog[i].subdirs[iter->index[i]].name, 11);
4423               strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4424               strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4425            }
4426            fname_to_str(buf, iter->catalog[iter->level].files[iter->index[iter->level]].name, 11);
4427            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
4428         }
4429#endif
4430         /* parse flags */
4431         if (fdr.flags & fdr99_f_program)
4432            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "PGM%s",
4433                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4434         else
4435            snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%c/%c %d%s",
4436                     (fdr.flags & fdr99_f_int) ? 'I' : 'D',
4437                     (fdr.flags & fdr99_f_var) ? 'V' : 'F',
4438                     fdr.reclen,
4439                     (fdr.flags & fdr99_f_wp) ? " R/O" : "");
4440         /* len in physrecs */
4441         ent->filesize = get_win_fdr_fphysrecs(&fdr);
4442
4443         iter->index[iter->level]++;
4444      }
4445   }
4446
4447   return 0;
4448}
4449
4450/*
4451   Compute free space on disk image (in AUs)
4452*/
4453static imgtoolerr_t ti99_image_freespace(imgtool_partition *partition, UINT64 *size)
4454{
4455   imgtool_image *img = imgtool_partition_image(partition);
4456   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4457   size_t freeAUs;
4458   int i;
4459
4460   freeAUs = 0;
4461   for (i=0; i<image->AUformat.totAUs; i++)
4462   {
4463      if (! (image->abm[i >> 3] & (1 << (i & 7))))
4464         freeAUs++;
4465   }
4466
4467   *size = freeAUs;
4468
4469   return IMGTOOLERR_SUCCESS;
4470}
4471
4472/*
4473   Extract a file from a ti99_image.  The file is saved in tifile format.
4474*/
4475static imgtoolerr_t ti99_image_readfile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *destf)
4476{
4477   imgtool_image *img = imgtool_partition_image(partition);
4478#if 1
4479
4480   /* extract data as TIFILES */
4481   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4482   ti99_lvl2_fileref src_file;
4483   ti99_lvl2_fileref dst_file;
4484   ti99_date_time date_time;
4485   int fphysrecs;
4486   int i;
4487   UINT8 buf[256];
4488   imgtoolerr_t errorcode;
4489
4490
4491   if (check_fpath(fpath))
4492      return IMGTOOLERR_BADFILENAME;
4493
4494   /* open file on TI image */
4495   switch (image->type)
4496   {
4497   case L2I_DSK:
4498      errorcode = open_file_lvl2_dsk(image, fpath, &src_file);
4499      break;
4500
4501   case L2I_WIN:
4502      errorcode = open_file_lvl2_win(image, fpath, &src_file);
4503      break;
4504
4505   default:
4506      errorcode = -1;
4507      break;
4508   }
4509   if (errorcode)
4510      return errorcode;
4511
4512   errorcode = new_file_lvl2_tifiles(destf, &dst_file);
4513   if (errorcode)
4514      return errorcode;
4515
4516   /* write TIFILE header */
4517   /* set up parameters */
4518   set_file_flags(&dst_file, get_file_flags(&src_file));
4519   set_file_recsperphysrec(&dst_file, get_file_recsperphysrec(&src_file));
4520   errorcode = set_file_fphysrecs(&dst_file, get_file_fphysrecs(&src_file));
4521   if (errorcode)
4522      return errorcode;
4523   set_file_eof(&dst_file, get_file_eof(&src_file));
4524   errorcode = set_file_reclen(&dst_file, get_file_reclen(&src_file));
4525   if (errorcode)
4526      return errorcode;
4527   errorcode = set_file_fixrecs(&dst_file, get_file_fixrecs(&src_file));
4528   if (errorcode)
4529      return errorcode;
4530
4531   get_file_creation_date(&src_file, &date_time);
4532   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4533         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4534      current_date_time(&date_time);*/
4535   set_file_creation_date(&dst_file, date_time);
4536
4537   get_file_update_date(&src_file, &date_time);
4538   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4539         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4540      current_date_time(&date_time);*/
4541   set_file_update_date(&dst_file, date_time);
4542
4543   if (stream_write(destf, & dst_file.u.tifiles.hdr, 128) != 128)
4544      return IMGTOOLERR_WRITEERROR;
4545
4546   /* copy data to TIFILE */
4547   fphysrecs = get_file_fphysrecs(&src_file);
4548
4549   for (i=0; i<fphysrecs; i++)
4550   {
4551      errorcode = read_file_physrec(& src_file, i, buf);
4552      if (errorcode)
4553         return errorcode;
4554
4555      errorcode = write_file_physrec(& dst_file, i, buf);
4556      if (errorcode)
4557         return errorcode;
4558   }
4559
4560   return 0;
4561
4562#else
4563
4564   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4565   ti99_lvl3_fileref src_file;
4566   UINT8 buf[256];
4567   int reclen;
4568   char lineend = '\r';
4569   int errorcode;
4570
4571
4572   if (check_fpath(fpath))
4573      return IMGTOOLERR_BADFILENAME;
4574
4575   /* open file on TI image */
4576   switch (image->type)
4577   {
4578   case L2I_DSK:
4579      errorcode = open_file_lvl2_dsk(image, fpath, &src_file.l2_file);
4580      break;
4581
4582   case L2I_WIN:
4583      errorcode = open_file_lvl2_win(image, fpath, &src_file.l2_file);
4584      break;
4585   }
4586   if (errorcode)
4587      return errorcode;
4588
4589   errorcode = open_file_lvl3(& src_file);
4590   if (errorcode)
4591      return errorcode;
4592
4593   /* write text data */
4594   while (! is_eof(& src_file))
4595   {
4596      errorcode = read_next_record(& src_file, buf, & reclen);
4597      if (errorcode)
4598         return errorcode;
4599      if (stream_write(destf, buf, reclen) != reclen)
4600         return IMGTOOLERR_WRITEERROR;
4601      if (stream_write(destf, &lineend, 1) != 1)
4602         return IMGTOOLERR_WRITEERROR;
4603   }
4604
4605   return 0;
4606
4607#endif
4608}
4609
4610/*
4611   Add a file to a ti99_image.  The file must be in tifile format.
4612*/
4613static imgtoolerr_t ti99_image_writefile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
4614{
4615   imgtool_image *img = imgtool_partition_image(partition);
4616   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4617   const char *filename;
4618   char ti_fname[10];
4619   ti99_lvl2_fileref src_file;
4620   ti99_lvl2_fileref dst_file;
4621   ti99_date_time date_time;
4622   int i;
4623   int fphysrecs;
4624   UINT8 buf[256];
4625   imgtoolerr_t errorcode;
4626   int parent_ref_valid, parent_ref = 0;
4627   ti99_catalog *catalog, catalog_buf = {0, };
4628
4629
4630   (void) writeoptions;
4631
4632   if (check_fpath(fpath))
4633      return IMGTOOLERR_BADFILENAME;
4634
4635   switch (image->type)
4636   {
4637   case L2I_DSK:
4638      errorcode = dsk_find_catalog_entry(image, fpath, &parent_ref_valid, &parent_ref, NULL, NULL);
4639      if (errorcode == 0)
4640         /* file already exists: causes an error for now */
4641         return IMGTOOLERR_UNEXPECTED;
4642      else if ((! parent_ref_valid) || (errorcode != IMGTOOLERR_FILENOTFOUND))
4643         return errorcode;
4644      break;
4645
4646   case L2I_WIN:
4647      errorcode = win_find_catalog_entry(image, fpath, &parent_ref_valid, &parent_ref, &catalog_buf, NULL, NULL);
4648      if (errorcode == 0)
4649         /* file already exists: causes an error for now */
4650         return IMGTOOLERR_UNEXPECTED;
4651      else if ((! parent_ref_valid) || (errorcode != IMGTOOLERR_FILENOTFOUND))
4652         return errorcode;
4653      break;
4654   }
4655
4656   errorcode = open_file_lvl2_tifiles(sourcef, & src_file);
4657   if (errorcode)
4658      return errorcode;
4659
4660   /* create new file */
4661   filename = strrchr(fpath, '.');
4662   if (filename)
4663      filename++;
4664   else
4665      filename = fpath;
4666   str_to_fname(ti_fname, filename);
4667   switch (image->type)
4668   {
4669   case L2I_DSK:
4670      errorcode = new_file_lvl2_dsk(image, parent_ref, ti_fname, &dst_file);
4671      if (errorcode)
4672         return errorcode;
4673      break;
4674
4675   case L2I_WIN:
4676      errorcode = new_file_lvl2_win(image, &catalog_buf, ti_fname, &dst_file);
4677      if (errorcode)
4678         return errorcode;
4679      break;
4680   }
4681
4682   /* set up parameters */
4683   set_file_flags(&dst_file, get_file_flags(&src_file));
4684   set_file_recsperphysrec(&dst_file, get_file_recsperphysrec(&src_file));
4685   errorcode = set_file_fphysrecs(&dst_file, /*get_file_fphysrecs(&src_file)*/0);
4686   if (errorcode)
4687      return errorcode;
4688   set_file_eof(&dst_file, get_file_eof(&src_file));
4689   errorcode = set_file_reclen(&dst_file, get_file_reclen(&src_file));
4690   if (errorcode)
4691      return errorcode;
4692   errorcode = set_file_fixrecs(&dst_file, get_file_fixrecs(&src_file));
4693   if (errorcode)
4694      return errorcode;
4695
4696   get_file_creation_date(&src_file, &date_time);
4697   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4698         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4699      current_date_time(&date_time);*/
4700   set_file_creation_date(&dst_file, date_time);
4701
4702   get_file_update_date(&src_file, &date_time);
4703   /*if ((date_time.time_MSB == 0) || (date_time.time_LSB == 0)
4704         || (date_time.date_MSB == 0) || (date_time.date_LSB == 0))
4705      current_date_time(&date_time);*/
4706   set_file_update_date(&dst_file, date_time);
4707
4708   /* alloc data physrecs */
4709   fphysrecs = get_file_fphysrecs(&src_file);
4710   switch (dst_file.type)
4711   {
4712   case L2F_DSK:
4713      errorcode = dsk_alloc_file_physrecs(&dst_file.u.dsk, fphysrecs);
4714      if (errorcode)
4715         return errorcode;
4716      break;
4717
4718   case L2F_WIN:
4719      errorcode = win_alloc_file_physrecs(&dst_file.u.win, fphysrecs);
4720      if (errorcode)
4721         return errorcode;
4722      break;
4723
4724   case L2F_TIFILES:
4725      break;
4726   }
4727
4728   /* copy data */
4729   for (i=0; i<fphysrecs; i++)
4730   {
4731      if (stream_read(sourcef, buf, 256) != 256)
4732         return IMGTOOLERR_READERROR;
4733
4734      errorcode = write_file_physrec(& dst_file, i, buf);
4735      if (errorcode)
4736         return errorcode;
4737   }
4738
4739   /* write fdr */
4740   switch (image->type)
4741   {
4742   case L2I_DSK:
4743      if (write_absolute_physrec(& image->l1_img, dst_file.u.dsk.fdr_aphysrec, &dst_file.u.dsk.fdr))
4744         return IMGTOOLERR_WRITEERROR;
4745      break;
4746
4747   case L2I_WIN:
4748      /* save fphysrecs field as well */
4749      if (dst_file.u.win.curfdr_aphysrec == dst_file.u.win.eldestfdr_aphysrec)
4750         set_win_fdr_fphysrecs(&dst_file.u.win.curfdr, dst_file.u.win.fphysrecs);
4751      if (write_absolute_physrec(& image->l1_img, dst_file.u.win.curfdr_aphysrec, &dst_file.u.win.curfdr))
4752         return IMGTOOLERR_WRITEERROR;
4753      if (dst_file.u.win.curfdr_aphysrec != dst_file.u.win.eldestfdr_aphysrec)
4754      {
4755         dst_file.u.win.curfdr_aphysrec = dst_file.u.win.eldestfdr_aphysrec;
4756         if (read_absolute_physrec(& image->l1_img, dst_file.u.win.curfdr_aphysrec, &dst_file.u.win.curfdr))
4757            return IMGTOOLERR_WRITEERROR;
4758         set_win_fdr_fphysrecs(&dst_file.u.win.curfdr, dst_file.u.win.fphysrecs);
4759         if (write_absolute_physrec(& image->l1_img, dst_file.u.win.curfdr_aphysrec, &dst_file.u.win.curfdr))
4760            return IMGTOOLERR_WRITEERROR;
4761      }
4762      break;
4763   }
4764
4765   /* update catalog */
4766   switch (image->type)
4767   {
4768   case L2I_DSK:
4769      catalog = &image->u.dsk.catalogs[parent_ref];
4770      for (i=0; i<128; i++)
4771      {
4772         buf[2*i] = catalog->files[i].fdr_ptr >> 8;
4773         buf[2*i+1] = catalog->files[i].fdr_ptr & 0xff;
4774      }
4775      if (write_absolute_physrec(& image->l1_img, image->u.dsk.fdir_aphysrec[parent_ref], buf))
4776         return IMGTOOLERR_WRITEERROR;
4777      break;
4778
4779   case L2I_WIN:
4780      {
4781         win_vib_ddr parent_ddr;
4782         int fdir_AU;
4783
4784         /* update VIB/DDR and get FDIR AU address */
4785         if (read_absolute_physrec(& image->l1_img, parent_ref * image->AUformat.physrecsperAU, &parent_ddr))
4786            return IMGTOOLERR_READERROR;
4787         parent_ddr.num_files = catalog_buf.num_files;
4788         if (write_absolute_physrec(& image->l1_img, parent_ref * image->AUformat.physrecsperAU, &parent_ddr))
4789            return IMGTOOLERR_WRITEERROR;
4790         fdir_AU = get_UINT16BE(parent_ddr.fdir_AU);
4791
4792         /* generate FDIR and save it */
4793         for (i=0; i<127; i++)
4794         {
4795            buf[2*i] = catalog_buf.files[i].fdr_ptr >> 8;
4796            buf[2*i+1] = catalog_buf.files[i].fdr_ptr & 0xff;
4797         }
4798         buf[254] = parent_ref >> 8;
4799         buf[255] = parent_ref & 0xff;
4800         if (write_absolute_physrec(& image->l1_img, fdir_AU * image->AUformat.physrecsperAU, buf))
4801            return IMGTOOLERR_WRITEERROR;
4802      }
4803      break;
4804   }
4805
4806   /* update bitmap */
4807   switch (image->type)
4808   {
4809   case L2I_DSK:
4810      {
4811         dsk_vib vib;
4812
4813         if (read_absolute_physrec(& image->l1_img, 0, &vib))
4814            return IMGTOOLERR_READERROR;
4815         memcpy(vib.abm, image->abm, 200);
4816         if (write_absolute_physrec(& image->l1_img, 0, &vib))
4817            return IMGTOOLERR_WRITEERROR;
4818      }
4819      break;
4820
4821   case L2I_WIN:
4822      /* save allocation bitmap (aphysrecs 1 through n, n<=33) */
4823      for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
4824         if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
4825            return IMGTOOLERR_WRITEERROR;
4826      break;
4827   }
4828
4829   return 0;
4830}
4831
4832/*
4833   Delete a file from a ti99_image.
4834*/
4835static imgtoolerr_t dsk_image_deletefile(imgtool_partition *partition, const char *fpath)
4836{
4837   imgtool_image *img = imgtool_partition_image(partition);
4838   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4839   dsk_fdr fdr;
4840   int i, cluster_index;
4841   unsigned cur_AU, cluster_lastfphysrec;
4842   int fphysrecs;
4843   int parent_ref, is_dir, catalog_index;
4844   imgtoolerr_t errorcode;
4845   UINT8 buf[256];
4846   ti99_catalog *catalog;
4847
4848
4849   if (check_fpath(fpath))
4850      return IMGTOOLERR_BADFILENAME;
4851
4852   errorcode = dsk_find_catalog_entry(image, fpath, NULL, &parent_ref, &is_dir, &catalog_index);
4853   if (errorcode)
4854      return errorcode;
4855
4856   if (is_dir)
4857   {
4858      catalog = &image->u.dsk.catalogs[catalog_index+1];
4859
4860      if ((catalog->num_files != 0) || (catalog->num_subdirs != 0))
4861         return IMGTOOLERR_UNIMPLEMENTED;
4862
4863      catalog = &image->u.dsk.catalogs[0];
4864
4865      /* free fdir AU */
4866      cur_AU = image->u.dsk.fdir_aphysrec[catalog_index+1] / image->AUformat.physrecsperAU;
4867      image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
4868
4869      /* delete catalog entry */
4870      for (i=catalog_index; i<2; i++)
4871      {
4872         catalog->subdirs[i] = catalog->subdirs[i+1];
4873         image->u.dsk.fdir_aphysrec[i+1] = image->u.dsk.fdir_aphysrec[i+2];
4874      }
4875      memset(catalog->subdirs[2].name, 0, 10);
4876      catalog->subdirs[2].dir_ptr = 0;
4877      image->u.dsk.fdir_aphysrec[3] = 0;
4878      catalog->num_subdirs--;
4879
4880      /* update directory and bitmap in vib */
4881      {
4882         dsk_vib vib;
4883
4884         if (read_absolute_physrec(& image->l1_img, 0, &vib))
4885            return IMGTOOLERR_READERROR;
4886
4887         for (i=0; i<3; i++)
4888         {
4889            memcpy(vib.subdir[i].name, catalog->subdirs[i].name, 10);
4890            set_UINT16BE(&vib.subdir[i].fdir_aphysrec, image->u.dsk.fdir_aphysrec[i+1]);
4891         }
4892
4893         memcpy(vib.abm, image->abm, 200);
4894
4895         if (write_absolute_physrec(& image->l1_img, 0, &vib))
4896            return IMGTOOLERR_WRITEERROR;
4897      }
4898   }
4899   else
4900   {
4901      catalog = &image->u.dsk.catalogs[parent_ref];
4902
4903      if (read_absolute_physrec(& image->l1_img, catalog->files[catalog_index].fdr_ptr, &fdr))
4904         return IMGTOOLERR_READERROR;
4905
4906      /* free data AUs */
4907      fphysrecs = get_UINT16BE(fdr.fphysrecs);
4908
4909      i = 0;
4910      cluster_index = 0;
4911      while (cluster_index < 76)
4912      {
4913         cur_AU = get_dsk_fdr_cluster_baseAU(image, & fdr, cluster_index);
4914         if (cur_AU == 0)
4915            /* end of cluster list */
4916            break;
4917         cluster_lastfphysrec = get_dsk_fdr_cluster_lastfphysrec(& fdr, cluster_index);
4918
4919         while (i<=cluster_lastfphysrec)
4920         {
4921            /* the condition below is an error, but it should not prevent
4922            us from deleting the file */
4923            if (cur_AU >= image->AUformat.totAUs)
4924               /*return IMGTOOLERR_CORRUPTIMAGE;*/
4925               break;
4926
4927            image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
4928
4929            i += image->AUformat.physrecsperAU;
4930            cur_AU++;
4931         }
4932
4933         cluster_index++;
4934      }
4935      /* the condition below is an error, but it should not prevent us from
4936      deleting the file */
4937      /*if (i<fphysrecs)
4938         return IMGTOOLERR_CORRUPTIMAGE;*/
4939
4940      /* free fdr AU */
4941      cur_AU = catalog->files[catalog_index].fdr_ptr / image->AUformat.physrecsperAU;
4942      image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
4943
4944      /* delete catalog entry */
4945      for (i=catalog_index; i<127; i++)
4946         catalog->files[i] = catalog->files[i+1];
4947      catalog->files[127].fdr_ptr = 0;
4948      catalog->num_files--;
4949
4950      /* update parent fdir */
4951      for (i=0; i<128; i++)
4952      {
4953         buf[2*i] = catalog->files[i].fdr_ptr >> 8;
4954         buf[2*i+1] = catalog->files[i].fdr_ptr & 0xff;
4955      }
4956      if (write_absolute_physrec(& image->l1_img, image->u.dsk.fdir_aphysrec[parent_ref], buf))
4957         return IMGTOOLERR_WRITEERROR;
4958
4959      /* update bitmap */
4960      {
4961         dsk_vib vib;
4962
4963         if (read_absolute_physrec(& image->l1_img, 0, &vib))
4964            return IMGTOOLERR_READERROR;
4965         memcpy(vib.abm, image->abm, 200);
4966         if (write_absolute_physrec(& image->l1_img, 0, &vib))
4967            return IMGTOOLERR_WRITEERROR;
4968      }
4969   }
4970
4971   return 0;
4972}
4973
4974static imgtoolerr_t win_image_deletefile(imgtool_partition *partition, const char *fpath)
4975{
4976   imgtool_image *img = imgtool_partition_image(partition);
4977   ti99_lvl2_imgref *image = (ti99_lvl2_imgref *) imgtool_image_extra_bytes(img);
4978   int parent_ddr_AU, is_dir, catalog_index;
4979   win_fdr fdr;
4980   int i;
4981   unsigned cur_AU, end_AU;
4982   unsigned curfdr_aphysrec;
4983   unsigned cursibFDR_index, endsibFDR_index = 0;
4984   int errorcode;
4985   UINT8 buf[256];
4986   ti99_catalog catalog;
4987
4988
4989   if (check_fpath(fpath))
4990      return IMGTOOLERR_BADFILENAME;
4991
4992   errorcode = win_find_catalog_entry(image, fpath, NULL, &parent_ddr_AU, &catalog, &is_dir, &catalog_index);
4993   if (errorcode)
4994      return errorcode;
4995
4996   if (is_dir)
4997   {
4998      unsigned DDR_AU;
4999      win_vib_ddr ddr_buf;
5000
5001      /* Read DDR record */
5002      DDR_AU = catalog.subdirs[catalog_index].dir_ptr;
5003      if (read_absolute_physrec(& image->l1_img, DDR_AU*image->AUformat.physrecsperAU, &ddr_buf))
5004         return IMGTOOLERR_READERROR;
5005
5006      /* read FDIR AU pointer */
5007      cur_AU = get_UINT16BE(ddr_buf.fdir_AU);
5008
5009      /* sanity checks */
5010      if ((ddr_buf.num_files > 127) || (ddr_buf.num_subdirs > 114) || (cur_AU > image->AUformat.totAUs))
5011         return IMGTOOLERR_CORRUPTIMAGE;
5012
5013      if ((ddr_buf.num_files != 0) || (ddr_buf.num_subdirs != 0))
5014         return IMGTOOLERR_UNIMPLEMENTED;
5015
5016      /* free fdir AU */
5017      image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
5018
5019      /* free ddr AU */
5020      image->abm[DDR_AU >> 3] &= ~ (1 << (DDR_AU & 7));
5021
5022      /* delete parent catalog entry */
5023      for (i=catalog_index; i<113; i++)
5024         catalog.subdirs[i] = catalog.subdirs[i+1];
5025      catalog.subdirs[114].dir_ptr = 0;
5026      catalog.num_subdirs--;
5027
5028      /* update parent VIB/DDR */
5029      if (read_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &ddr_buf))
5030         return IMGTOOLERR_READERROR;
5031      ddr_buf.num_subdirs = catalog.num_subdirs;
5032      for (i=0; i<114; i++)
5033         set_UINT16BE(&ddr_buf.subdir_AU[i], catalog.subdirs[i].dir_ptr);
5034      if (write_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &ddr_buf))
5035         return IMGTOOLERR_WRITEERROR;
5036
5037      /* save allocation bitmap (aphysrecs 1 through n, n<=33) */
5038      for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
5039         if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
5040            return IMGTOOLERR_WRITEERROR;
5041   }
5042   else
5043   {
5044      /* check integrity of FDR sibling chain, and go to last sibling */
5045      /* note that as we check that the back chain is consistent with the forward
5046      chain, we will also detect any cycle in the sibling chain, so we do not
5047      need to check against them explicitely */
5048      {
5049         int pastendoflist_flag;
5050         unsigned prevfdr_aphysrec;
5051
5052
5053         pastendoflist_flag = 0;
5054         cursibFDR_index = 0;
5055         curfdr_aphysrec = catalog.files[catalog_index].fdr_ptr * image->AUformat.physrecsperAU;
5056         if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
5057            return IMGTOOLERR_READERROR;
5058
5059         if (get_UINT16BE(fdr.prevsibFDR_AU) != 0)
5060            return IMGTOOLERR_CORRUPTIMAGE;
5061
5062         while (1)
5063         {
5064            if (! pastendoflist_flag)
5065            {
5066               /* look for end of list */
5067               for (i=0; i<54; i++)
5068               {
5069                  if (get_UINT16BE(fdr.clusters[i][0]) == 0)
5070                  {
5071                     endsibFDR_index = cursibFDR_index;
5072                     pastendoflist_flag = TRUE;
5073                     break;
5074                  }
5075               }
5076            }
5077
5078            /* exit loop if end of sibling chain */
5079            if (! get_UINT16BE(fdr.nextsibFDR_AU))
5080               break;
5081
5082            /* otherwise read next FDR */
5083            if (get_UINT16BE(fdr.nextsibFDR_AU) >= image->AUformat.totAUs)
5084               return IMGTOOLERR_CORRUPTIMAGE;
5085
5086            prevfdr_aphysrec = curfdr_aphysrec;
5087            curfdr_aphysrec = get_win_fdr_nextsibFDR_aphysrec(image, &fdr);
5088            if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
5089               return IMGTOOLERR_READERROR;
5090            cursibFDR_index++;
5091
5092            /* check that back chaining is consistent with forward chaining */
5093            if (get_win_fdr_prevsibFDR_aphysrec(image, &fdr) != prevfdr_aphysrec)
5094               return IMGTOOLERR_CORRUPTIMAGE;
5095         }
5096         if (! pastendoflist_flag)
5097            endsibFDR_index = cursibFDR_index;
5098      }
5099
5100
5101      while (1)
5102      {
5103         if (cursibFDR_index <= endsibFDR_index)
5104         {
5105
5106            for (i = 0; i < 54; i++)
5107            {
5108               cur_AU = get_UINT16BE(fdr.clusters[i][0]);
5109               if (cur_AU == 0)
5110                  /* end of cluster list */
5111                  break;
5112               end_AU = get_UINT16BE(fdr.clusters[i][1]);
5113
5114               while (cur_AU<=end_AU)
5115               {
5116                  /* the condition below is an error, but it should not prevent
5117                  us from deleting the file */
5118                  if (cur_AU >= image->AUformat.totAUs)
5119                     /*return IMGTOOLERR_CORRUPTIMAGE;*/
5120                     break;
5121
5122                  image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
5123
5124                  cur_AU++;
5125               }
5126            }
5127         }
5128
5129         /* free fdr AU if applicable */
5130         if ((curfdr_aphysrec % image->AUformat.physrecsperAU) == 0)
5131         {
5132            cur_AU = curfdr_aphysrec / image->AUformat.physrecsperAU;
5133            image->abm[cur_AU >> 3] &= ~ (1 << (cur_AU & 7));
5134         }
5135
5136         if (cursibFDR_index == 0)
5137            break;
5138         curfdr_aphysrec = get_win_fdr_prevsibFDR_aphysrec(image, &fdr);
5139         if (read_absolute_physrec(& image->l1_img, curfdr_aphysrec, &fdr))
5140            return IMGTOOLERR_READERROR;
5141         cursibFDR_index--;
5142      }
5143
5144
5145      /* delete catalog entry */
5146      for (i=catalog_index; i<127; i++)
5147         catalog.files[i] = catalog.files[i+1];
5148      catalog.files[127].fdr_ptr = 0;
5149      catalog.num_files--;
5150
5151
5152      /* update VIB/DDR and get FDIR AU address */
5153      {
5154         win_vib_ddr parent_ddr;
5155
5156         if (read_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &parent_ddr))
5157            return IMGTOOLERR_READERROR;
5158         parent_ddr.num_files = catalog.num_files;
5159         if (write_absolute_physrec(& image->l1_img, parent_ddr_AU * image->AUformat.physrecsperAU, &parent_ddr))
5160            return IMGTOOLERR_WRITEERROR;
5161         cur_AU = get_UINT16BE(parent_ddr.fdir_AU);
5162      }
5163
5164      /* generate FDIR and save it */
5165      for (i=0; i<127; i++)
5166      {
5167         buf[2*i] = catalog.files[i].fdr_ptr >> 8;
5168         buf[2*i+1] = catalog.files[i].fdr_ptr & 0xff;
5169      }
5170      buf[254] = parent_ddr_AU >> 8;
5171      buf[255] = parent_ddr_AU & 0xff;
5172      if (write_absolute_physrec(& image->l1_img, cur_AU * image->AUformat.physrecsperAU, buf))
5173         return IMGTOOLERR_WRITEERROR;
5174
5175      /* save allocation bitmap (aphysrecs 1 through n, n<=33) */
5176      for (i=0; i < (image->AUformat.totAUs+2047)/2048; i++)
5177         if (write_absolute_physrec(&image->l1_img, i+1, image->abm+i*256))
5178            return IMGTOOLERR_WRITEERROR;
5179   }
5180
5181   return 0;
5182}
5183
5184/*
5185   Create a blank ti99_image (common code).
5186
5187   Supports MESS and V9T9 formats only
5188*/
5189static imgtoolerr_t dsk_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions, ti99_img_format img_format)
5190{
5191   const char *volname;
5192   int density;
5193   ti99_lvl1_imgref l1_img;
5194   int protected;
5195
5196   int totphysrecs, physrecsperAU, totAUs;
5197
5198   dsk_vib vib;
5199   UINT8 empty_sec[256];
5200
5201   int i;
5202
5203   l1_img.img_format = img_format;
5204   l1_img.file_handle = f;
5205
5206   /* read options */
5207   volname = option_resolution_lookup_string(createoptions, dsk_createopts_volname);
5208   l1_img.geometry.heads = option_resolution_lookup_int(createoptions, dsk_createopts_sides);
5209   l1_img.geometry.cylinders = option_resolution_lookup_int(createoptions, dsk_createopts_tracks);
5210   l1_img.geometry.secspertrack = option_resolution_lookup_int(createoptions, dsk_createopts_sectors);
5211   protected = option_resolution_lookup_int(createoptions, dsk_createopts_protection);
5212   density = option_resolution_lookup_int(createoptions, dsk_createopts_density);
5213
5214   /* NPW 03-DEC-2003 - Fixes a crash if volname is NULL */
5215   if (!volname)
5216      volname = "";
5217
5218   totphysrecs = l1_img.geometry.secspertrack * l1_img.geometry.cylinders * l1_img.geometry.heads;
5219   physrecsperAU = (totphysrecs + 1599) / 1600;
5220   /* round to next larger power of 2 */
5221   for (i = 1; i < physrecsperAU; i <<= 1)
5222      ;
5223   physrecsperAU = i;
5224   totAUs = totphysrecs / physrecsperAU;
5225
5226   /* auto-density */
5227   if (density == 0)
5228   {
5229      if (l1_img.geometry.secspertrack <= 9)
5230         density = 1;
5231      else if (l1_img.geometry.secspertrack <= 18)
5232         density = 2;
5233      else
5234         density = 3;
5235   }
5236
5237   /* check volume name */
5238   if (strchr(volname, '.') || strchr(volname, ' ') || (strlen(volname) > 10))
5239      return /*IMGTOOLERR_BADFILENAME*/IMGTOOLERR_PARAMCORRUPT;
5240
5241   /* FM disks can hold fewer sector per track than MFM disks */
5242   if ((density == 1) && (l1_img.geometry.secspertrack > 9))
5243      return IMGTOOLERR_PARAMTOOLARGE;
5244
5245   /* DD disks can hold fewer sector per track than HD disks */
5246   if ((density == 2) && (l1_img.geometry.secspertrack > 18))
5247      return IMGTOOLERR_PARAMTOOLARGE;
5248
5249   /* check total disk size */
5250   if (totphysrecs < 2)
5251      return IMGTOOLERR_PARAMTOOSMALL;
5252
5253   /* initialize vib in aphysrec 0 */
5254
5255   /* set volume name */
5256   str_to_fname(vib.name, volname);
5257
5258   /* set every header field */
5259   set_UINT16BE(& vib.totphysrecs, totphysrecs);
5260   vib.secspertrack = l1_img.geometry.secspertrack;
5261   vib.id[0] = 'D';
5262   vib.id[1] = 'S';
5263   vib.id[2] = 'K';
5264   vib.protection = protected ? 'P' : ' ';
5265   vib.cylinders = l1_img.geometry.cylinders;
5266   vib.heads = l1_img.geometry.heads;
5267   vib.density = density;
5268   for (i=0; i<3; i++)
5269   {
5270      memset(vib.subdir[i].name, '\0', 10);
5271      set_UINT16BE(& vib.subdir[i].fdir_aphysrec, 0);
5272   }
5273
5274   /* clear bitmap */
5275   for (i=0; i < (totAUs>>3); i++)
5276      vib.abm[i] = 0;
5277
5278   if (totAUs & 7)
5279   {
5280      vib.abm[i] = 0xff << (totAUs & 7);
5281      i++;
5282   }
5283
5284   for (; i < 200; i++)
5285      vib.abm[i] = 0xff;
5286
5287   /* mark first 2 aphysrecs (vib and fdir) as used */
5288   vib.abm[0] |= (physrecsperAU == 1) ? 3 : 1;
5289
5290   /* write aphysrec 0 */
5291   if (write_absolute_physrec(& l1_img, 0, &vib))
5292      return IMGTOOLERR_WRITEERROR;
5293
5294
5295   /* now clear every other physrecs, including the FDIR record */
5296   memset(empty_sec, 0, 256);
5297
5298   for (i=1; i<totphysrecs; i++)
5299      if (write_absolute_physrec(& l1_img, i, empty_sec))
5300         return IMGTOOLERR_WRITEERROR;
5301
5302
5303   return dsk_image_init(image, f, img_format);
5304}
5305
5306/*
5307   Create a blank ti99_image (MESS format).
5308*/
5309static imgtoolerr_t dsk_image_create_mess(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions)
5310{
5311   return dsk_image_create(image, f, createoptions, if_mess);
5312}
5313
5314/*
5315   Create a blank ti99_image (V9T9 format).
5316*/
5317static imgtoolerr_t dsk_image_create_v9t9(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions)
5318{
5319   return dsk_image_create(image, f, createoptions, if_v9t9);
5320}
src/mess/tools/imgtool/modules/mac.c
r0r1340
1/****************************************************************************
2
3   mac.c
4
5   Handlers for Classic MacOS images (MFS and HFS formats).
6
7   Raphael Nabet, 2003
8
9   TODO:
10   * add support for HFS write
11
12*****************************************************************************
13
14   terminology:
15   disk block: 512-byte logical block.  With sectors of 512 bytes, one logical
16      block is equivalent to one sector; when the sector size is not 512
17      bytes, sectors are split or grouped to make 512-byte disk blocks.
18   allocation block: The File Manager always allocates logical disk blocks to
19      a file in groups called allocation blocks; an allocation block is
20      simply a group of consecutive logical blocks.  The size of a volume's
21      allocation blocks depends on the capacity of the volume; there can be
22      at most 4094 (MFS) or 65535 (HFS) allocation blocks on a volume.
23   MFS (Macintosh File System): File system used by the early Macintosh.  This
24      File system does not support folders (you may create folders on a MFS
25      disk, but such folders are not implemented on File System level but in
26      the Desktop file, and they are just a hint of how programs should list
27      files, i.e. you can't have two files with the same name on a volume
28      even if they are in two different folders), and it is not adequate for
29      large volumes.
30   HFS (Hierarchical File System): File system introduced with the HD20
31      harddisk, the Macintosh Plus ROMs, and system 3.2 (IIRC).  Contrary to
32      MFS, it supports hierarchical folders.  Also, it is suitable for larger
33      volumes.
34   HFS+ (HFS Plus): New file system introduced with MacOS 8.1.  It has a lot
35      in common with HFS, but it supports more allocation blocks (up to 4
36      billions IIRC), and many extra features, including longer file names
37      (up to 255 UTF-16 Unicode chars).
38   tag data: with the GCR encoding, each disk block is associated with a 12
39      (3.5" floppies) or 20 (HD20) byte tag record.  This tag record contains
40      information on the block allocation status (whether it is allocated
41      in a file or free, which file is it belongs to, what offset the block
42      has in the file).  This enables to recover all files whose data blocks
43      are still on the disk surface even if the disk catalog has been trashed
44      completely (though most file properties, like the name, type and
45      logical EOF, are not saved in the tag record and cannot be recovered).
46
47   Organization of an MFS volume:
48
49   Logical      Contents                           Allocation block
50   block
51
52   0 - 1:      System startup information
53   2 - m:      Master directory block (MDB)
54            + allocation block link pointers
55   m+1 - n:   Directory file
56   n+1 - p-2:   Other files and free space               0 - ((p-2)-(n+1))/k
57   p-1:      Alternate MDB
58   p:         Not used
59   usually, k = 2, m = 3, n = 16, p = 799 (SSDD 3.5" floppy)
60   with DSDD 3.5" floppy, I assume that p = 1599, but I don't know the other
61   values
62
63
64   Master Directory Block:
65
66   Offset  Length  Description
67   ------  ------  -----------
68        0       2  Volume Signature
69       2       4  Creation Date
70       6       4  Last Modification Date
71       10       2  Volume Attributes
72      12       2  Number of Files In Root Directory
73      14       2  First Block of Volume Bitmap
74      ...
75
76   Links:
77      http://developer.apple.com/documentation/mac/Files/Files-99.html
78      http://developer.apple.com/documentation/mac/Files/Files-100.html
79      http://developer.apple.com/documentation/mac/Files/Files-101.html
80      http://developer.apple.com/documentation/mac/Files/Files-102.html
81      http://developer.apple.com/documentation/mac/Files/Files-103.html
82      http://developer.apple.com/documentation/mac/Files/Files-104.html
83      http://developer.apple.com/documentation/mac/Files/Files-105.html
84      http://developer.apple.com/documentation/mac/Files/Files-106.html
85      http://developer.apple.com/documentation/mac/Devices/Devices-121.html#MARKER-2-169
86      http://developer.apple.com/documentation/mac/MoreToolbox/MoreToolbox-99.html
87
88*****************************************************************************/
89
90#include <ctype.h>
91#include <string.h>
92#include <time.h>
93#include <limits.h>
94#include <stddef.h>
95
96#include "osdepend.h"
97#include "imgtoolx.h"
98#include "macutil.h"
99#include "iflopimg.h"
100#include "formats/ap_dsk35.h"
101
102/* if 1, check consistency of B-Tree (most of the checks will eventually be
103   suppressed when the image is opened as read-only and only enabled when
104   the image is opened as read/write) */
105#define BTREE_CHECKS 1
106/* if 1, check consistency of tag data when we are at risk of corrupting the
107   disk (file write and allocation) */
108#define TAG_CHECKS 1
109/* if 1, check consistency of tag data when reading files (not recommended
110   IMHO) */
111#define TAG_EXTRA_CHECKS 0
112
113#if 0
114#pragma mark MISCELLANEOUS UTILITIES
115#endif
116
117typedef struct UINT16BE
118{
119   UINT8 bytes[2];
120} UINT16BE;
121
122typedef struct UINT24BE
123{
124   UINT8 bytes[3];
125} UINT24BE;
126
127typedef struct UINT32BE
128{
129   UINT8 bytes[4];
130} UINT32BE;
131
132INLINE UINT16 get_UINT16BE(UINT16BE word)
133{
134   return (word.bytes[0] << 8) | word.bytes[1];
135}
136
137INLINE void set_UINT16BE(UINT16BE *word, UINT16 data)
138{
139   word->bytes[0] = (data >> 8) & 0xff;
140   word->bytes[1] = data & 0xff;
141}
142
143INLINE UINT32 get_UINT24BE(UINT24BE word)
144{
145   return (word.bytes[0] << 16) | (word.bytes[1] << 8) | word.bytes[2];
146}
147
148INLINE void set_UINT24BE(UINT24BE *word, UINT32 data)
149{
150   word->bytes[0] = (data >> 16) & 0xff;
151   word->bytes[1] = (data >> 8) & 0xff;
152   word->bytes[2] = data & 0xff;
153}
154
155INLINE UINT32 get_UINT32BE(UINT32BE word)
156{
157   return (word.bytes[0] << 24) | (word.bytes[1] << 16) | (word.bytes[2] << 8) | word.bytes[3];
158}
159
160INLINE void set_UINT32BE(UINT32BE *word, UINT32 data)
161{
162   word->bytes[0] = (data >> 24) & 0xff;
163   word->bytes[1] = (data >> 16) & 0xff;
164   word->bytes[2] = (data >> 8) & 0xff;
165   word->bytes[3] = data & 0xff;
166}
167
168/*
169   Macintosh string: first byte is length
170*/
171typedef UINT8 mac_str27[28];
172typedef UINT8 mac_str31[32];
173typedef UINT8 mac_str63[64];
174typedef UINT8 mac_str255[256];
175
176/*
177   Macintosh type/creator code: 4 char value
178*/
179typedef UINT32BE mac_type;
180
181/*
182   point record, with the y and x coordinates
183*/
184typedef struct mac_point
185{
186   UINT16BE v;      /* actually signed */
187   UINT16BE h;      /* actually signed */
188} mac_point;
189
190/*
191   rect record, with the corner coordinates
192*/
193typedef struct mac_rect
194{
195   UINT16BE top;   /* actually signed */
196   UINT16BE left;   /* actually signed */
197   UINT16BE bottom;/* actually signed */
198   UINT16BE right;   /* actually signed */
199} mac_rect;
200
201/*
202   FInfo (Finder file info) record
203*/
204typedef struct mac_FInfo
205{
206   mac_type  type;         /* file type */
207   mac_type  creator;      /* file creator */
208   UINT16BE  flags;      /* Finder flags */
209   mac_point location;      /* file's location in window */
210                        /* If set to {0, 0}, and the inited flag is
211                        clear, the Finder will place the item
212                        automatically */
213   UINT16BE  fldr;         /* MFS: window that contains file */
214                        /* -3: trash */
215                        /* -2: desktop */
216                        /* -1: new folder template?????? */
217                        /* 0: disk window ("root") */
218                        /* > 0: specific folder, index of FOBJ resource??? */
219                        /* The FOBJ resource contains some folder info;
220                        the name of the resource is the folder name. */
221                     /* HFS & HFS+:
222                        System 7: The window in which the file’s icon appears
223                        System 8: reserved (set to 0) */
224} mac_FInfo;
225
226/*
227   FXInfo (Finder extended file info) record -- not found in MFS
228*/
229typedef struct mac_FXInfo
230{
231   UINT16BE iconID;      /* System 7: An ID number for the file’s icon; the
232                        numbers that identify icons are assigned by the
233                        Finder */
234                     /* System 8: Reserved (set to 0) */
235   UINT16BE reserved[3];   /* Reserved (set to 0) */
236   UINT8    script;      /* System 7: if high-bit is set, the script code
237                        for displaying the file name; ignored otherwise */
238                     /* System 8: Extended flags MSB(?) */
239   UINT8    XFlags;      /* Extended flags */
240   UINT16BE comment;      /* System 7: Comment ID if high-bit is clear */
241                     /* System 8: Reserved (set to 0) */
242   UINT32BE putAway;      /* Put away folder ID (i.e. if the user moves the
243                        file onto the desktop, the directory ID of the
244                        folder from which the user moves the file is
245                        saved here) */
246} mac_FXInfo;
247
248/*
249   DInfo (Finder folder info) record -- not found in MFS
250*/
251typedef struct mac_DInfo
252{
253   mac_rect rect;         /* Folder's window bounds */
254   UINT16BE flags;         /* Finder flags, e.g. kIsInvisible, kNameLocked, etc */
255   mac_point location;      /* Location of the folder in parent window */
256                        /* If set to {0, 0}, and the initied flag is
257                        clear, the Finder will place the item
258                        automatically */
259   UINT16BE view;         /* System 7: The manner in which folders are
260                        displayed */
261                     /* System 8: reserved (set to 0) */
262} mac_DInfo;
263
264/*
265   DXInfo (Finder extended folder info) record -- not found in MFS
266*/
267typedef struct mac_DXInfo
268{
269   mac_point scroll;      /* Scroll position */
270   UINT32BE openChain;      /* System 7: chain of directory IDs for open folders */
271                     /* System 8: reserved (set to 0) */
272   UINT8    script;      /* System 7: if high-bit is set, the script code
273                        for displaying the folder name; ignored otherwise */
274                     /* System 8: Extended flags MSB(?) */
275   UINT8    XFlags;      /* Extended flags */
276   UINT16BE comment;      /* System 7: Comment ID if high-bit is clear */
277                     /* System 8: Reserved (set to 0) */
278   UINT32BE putAway;      /* Put away folder ID (i.e. if the user moves the
279                        folder onto the desktop, the directory ID of
280                        the folder from which the user moves it is
281                        saved here) */
282} mac_DXInfo;
283
284/*
285   defines for FInfo & DInfo flags fields
286*/
287enum
288{
289   fif_isOnDesk         = 0x0001,   /* System 6: set if item is located on desktop (files and folders) */
290                              /* System 7: Unused (set to 0) */
291   fif_color            = 0x000E,   /* color coding (files and folders) */
292   fif_colorReserved      = 0x0010,   /* System 6: reserved??? */
293                              /* System 7: Unused (set to 0) */
294   fif_requiresSwitchLaunch= 0x0020,   /* System 6: ??? */
295                              /* System 7: Unused (set to 0) */
296   fif_isShared         = 0x0040,   /* Applications files: if set, the */
297                                 /* application can be executed by */
298                                 /* multiple users simultaneously. */
299                              /* Otherwise, set to 0. */
300   fif_hasNoINITs         = 0x0080,   /* Extensions/Control Panels: if set(?), */
301                                 /* this file contains no INIT */
302                                 /* resource */
303                              /* Otherwise, set to 0. */
304   fif_hasBeenInited      = 0x0100,   /* System 6: The Finder has recorded information from
305                                 the file’s bundle resource into the desktop
306                                 database and given the file or folder a
307                                 position on the desktop. */
308                              /* System 7? 8?: Clear if the file contains desktop database */
309                                 /* resources ('BNDL', 'FREF', 'open', 'kind'...) */
310                                 /* that have not been added yet. Set only by the Finder */
311                                 /* Reserved for folders - make sure this bit is cleared for folders */
312
313   /* bit 0x0200 was at a point (AOCE for system 7.x?) the letter bit for
314   AOCE, but was reserved before and it is reserved again in recent MacOS
315   releases. */
316
317   fif_hasCustomIcon      = 0x0400,   /* (files and folders) */
318   fif_isStationery      = 0x0800,   /* System 7: (files only) */
319   fif_nameLocked         = 0x1000,   /* (files and folders) */
320   fif_hasBundle         = 0x2000,   /* Files only */
321   fif_isInvisible         = 0x4000,   /* (files and folders) */
322   fif_isAlias            = 0x8000   /* System 7: (files only) */
323};
324
325/*
326   mac_to_c_strncpy()
327
328   Encode a macintosh string as a C string.  The NUL character is escaped,
329   using the "%00" sequence.  To avoid any ambiguity, '%' is escaped with
330   '%25'.
331
332   dst (O): C string
333   n (I): length of buffer pointed to by dst
334   src (I): macintosh string (first byte is length)
335*/
336static void mac_to_c_strncpy(char *dst, int n, UINT8 *src)
337{
338   size_t len = src[0];
339   int i, j;
340
341   i = j = 0;
342   while ((i < len) && (j < n-1))
343   {
344      switch (src[i+1])
345      {
346      case '\0':
347         if (j >= n-3)
348            goto exit;
349         dst[j] = '%';
350         dst[j+1] = '0';
351         dst[j+2] = '0';
352         j += 3;
353         break;
354
355      case '%':
356         if (j >= n-3)
357            goto exit;
358         dst[j] = '%';
359         dst[j+1] = '2';
360         dst[j+2] = '5';
361         j += 3;
362         break;
363
364      default:
365         dst[j] = src[i+1];
366         j++;
367         break;
368      }
369      i++;
370   }
371
372exit:
373   if (n > 0)
374      dst[j] = '\0';
375}
376
377/*
378   c_to_mac_strncpy()
379
380   Decode a C string to a macintosh string.  The NUL character is escaped,
381   using the "%00" sequence.  To avoid any ambiguity, '%' is escaped with
382   '%25'.
383
384   dst (O): macintosh string (first byte is length)
385   src (I): C string
386   n (I): length of string pointed to by src
387*/
388static void c_to_mac_strncpy(mac_str255 dst, const char *src, int n)
389{
390   size_t len;
391   int i;
392   char buf[3];
393
394
395   len = 0;
396   i = 0;
397   while ((i < n) && (len < 255))
398   {
399      switch (src[i])
400      {
401      case '%':
402         if (i >= n-2)
403            goto exit;
404         buf[0] = src[i+1];
405         buf[1] = src[i+2];
406         buf[2] = '\0';
407         dst[len+1] = strtoul(buf, NULL, 16);
408         i += 3;
409         break;
410
411      default:
412         dst[len+1] = src[i];
413         i++;
414         break;
415      }
416      len++;
417   }
418
419exit:
420   dst[0] = len;
421}
422
423/*
424   mac_strcmp()
425
426   Compare two macintosh strings
427
428   s1 (I): the string to compare
429   s2 (I): the comparison string
430
431   Return a zero if s1 and s2 are equal, a negative value if s1 is less than
432   s2, and a positive value if s1 is greater than s2.
433*/
434/*static int mac_strcmp(const UINT8 *s1, const UINT8 *s2)
435{
436   size_t common_len;
437
438   common_len = (s1[0] <= s2[0]) ? s1[0] : s2[0];
439
440   return memcmp(s1+1, s2+1, common_len) || ((int)s1[0] - s2[0]);
441}*/
442
443/*
444   mac_stricmp()
445
446   Compare two macintosh strings in a manner compatible with the macintosh HFS
447   file system.
448
449   This functions emulates the way HFS (and MFS???) sorts string: this is
450   equivalent to the RelString macintosh toolbox call with the caseSensitive
451   parameter as false and the diacSensitive parameter as true.
452
453   s1 (I): the string to compare
454   s2 (I): the comparison string
455
456   Return a zero if s1 and s2 are equal, a negative value if s1 is less than
457   s2, and a positive value if s1 is greater than s2.
458
459Known issues:
460   Using this function makes sense with the MacRoman encoding, as it means the
461   computer will regard "DeskTop File", "Desktop File", "Desktop file", etc,
462   as the same file.  (UNIX users will probably regard this as an heresy, but
463   you must consider that, unlike UNIX, the Macintosh was not designed for
464   droids, but error-prone human beings that may forget about case.)
465
466   (Also, letters with diatrical signs follow the corresponding letters
467   without diacritical signs in the HFS catalog file.  This does not matter,
468   though, since the Finder will not display files in the HFS catalog order,
469   but it will instead sort files according to whatever order is currently
470   selected in the View menu.)
471
472   However, with other text encodings, the behavior will be completely absurd.
473   For instance, with the Greek encoding, it will think that the degree symbol
474   is the same letter (with different case) as the upper-case Psi, so that if
475   a program asks for a file called "90°" on a greek HFS volume, and there is
476   a file called "90Ψ" on this volume, file "90Ψ" will be opened.
477   Results will probably be even weirder with 2-byte scripts like Japanese or
478   Chinese.  Of course, we are not going to fix this issue, since doing so
479   would break the compatibility with the original Macintosh OS.
480*/
481
482static int mac_stricmp(const UINT8 *s1, const UINT8 *s2)
483{
484   static const unsigned char mac_char_sort_table[256] =
485   {
486   /*   \x00   \x01   \x02   \x03   \x04   \x05   \x06   \x07 */
487      0x00,   0x01,   0x02,   0x03,   0x04,   0x05,   0x06,   0x07,
488   /*   \x08   \x09   \x0a   \x0b   \x0c   \x0d   \x0e   \x0f */
489      0x08,   0x09,   0x0a,   0x0b,   0x0c,   0x0d,   0x0e,   0x0f,
490   /*   \x10   \x11   \x12   \x13   \x14   \x15   \x16   \x17 */
491      0x10,   0x11,   0x12,   0x13,   0x14,   0x15,   0x16,   0x17,
492   /*   \x18   \x19   \x1a   \x1b   \x1c   \x1d   \x1e   \x1f */
493      0x18,   0x19,   0x1a,   0x1b,   0x1c,   0x1d,   0x1e,   0x1f,
494   /*   \x20   \x21   \x22   \x23   \x24   \x25   \x26   \x27 */
495      0x20,   0x21,   0x22,   0x27,   0x28,   0x29,   0x2a,   0x2b,
496   /*   \x28   \x29   \x2a   \x2b   \x2c   \x2d   \x2e   \x2f */
497      0x2e,   0x2f,   0x30,   0x31,   0x32,   0x33,   0x34,   0x35,
498   /*   \x30   \x31   \x32   \x33   \x34   \x35   \x36   \x37 */
499      0x36,   0x37,   0x38,   0x39,   0x3a,   0x3b,   0x3c,   0x3d,
500   /*   \x38   \x39   \x3a   \x3b   \x3c   \x3d   \x3e   \x3f */
501      0x3e,   0x3f,   0x40,   0x41,   0x42,   0x43,   0x44,   0x45,
502   /*   \x40   \x41   \x42   \x43   \x44   \x45   \x46   \x47 */
503      0x46,   0x47,   0x51,   0x52,   0x54,   0x55,   0x5a,   0x5b,
504   /*   \x48   \x49   \x4a   \x4b   \x4c   \x4d   \x4e   \x4f */
505      0x5c,   0x5d,   0x62,   0x63,   0x64,   0x65,   0x66,   0x68,
506   /*   \x50   \x51   \x52   \x53   \x54   \x55   \x56   \x57 */
507      0x71,   0x72,   0x73,   0x74,   0x76,   0x77,   0x7c,   0x7d,
508   /*   \x58   \x59   \x5a   \x5b   \x5c   \x5d   \x5e   \x5f */
509      0x7e,   0x7f,   0x81,   0x82,   0x83,   0x84,   0x85,   0x86,
510   /*   \x60   \x61   \x62   \x63   \x64   \x65   \x66   \x67 */
511      0x4d,   0x47,   0x51,   0x52,   0x54,   0x55,   0x5a,   0x5b,
512   /*   \x68   \x69   \x6a   \x6b   \x6c   \x6d   \x6e   \x6f */
513      0x5c,   0x5d,   0x62,   0x63,   0x64,   0x65,   0x66,   0x68,
514   /*   \x70   \x71   \x72   \x73   \x74   \x75   \x76   \x77 */
515      0x71,   0x72,   0x73,   0x74,   0x76,   0x77,   0x7c,   0x7d,
516   /*   \x78   \x79   \x7a   \x7b   \x7c   \x7d   \x7e   \x7f */
517      0x7e,   0x7f,   0x81,   0x87,   0x88,   0x89,   0x8a,   0x8b,
518   /*   \x80   \x81   \x82   \x83   \x84   \x85   \x86   \x87 */
519      0x49,   0x4b,   0x53,   0x56,   0x67,   0x69,   0x78,   0x4e,
520   /*   \x88   \x89   \x8a   \x8b   \x8c   \x8d   \x8e   \x8f */
521      0x48,   0x4f,   0x49,   0x4a,   0x4b,   0x53,   0x56,   0x57,
522   /*   \x90   \x91   \x92   \x93   \x94   \x95   \x96   \x97 */
523      0x58,   0x59,   0x5e,   0x5f,   0x60,   0x61,   0x67,   0x6d,
524   /*   \x98   \x99   \x9a   \x9b   \x9c   \x9d   \x9e   \x9f */
525      0x6e,   0x6f,   0x69,   0x6a,   0x79,   0x7a,   0x7b,   0x78,
526   /*   \xa0   \xa1   \xa2   \xa3   \xa4   \xa5   \xa6   \xa7 */
527      0x8c,   0x8d,   0x8e,   0x8f,   0x90,   0x91,   0x92,   0x75,
528   /*   \xa8   \xa9   \xaa   \xab   \xac   \xad   \xae   \xaf */
529      0x93,   0x94,   0x95,   0x96,   0x97,   0x98,   0x4c,   0x6b,
530   /*   \xb0   \xb1   \xb2   \xb3   \xb4   \xb5   \xb6   \xb7 */
531      0x99,   0x9a,   0x9b,   0x9c,   0x9d,   0x9e,   0x9f,   0xa0,
532   /*   \xb8   \xb9   \xba   \xbb   \xbc   \xbd   \xbe   \xbf */
533      0xa1,   0xa2,   0xa3,   0x50,   0x70,   0xa4,   0x4c,   0x6b,
534   /*   \xc0   \xc1   \xc2   \xc3   \xc4   \xc5   \xc6   \xc7 */
535      0xa5,   0xa6,   0xa7,   0xa8,   0xa9,   0xaa,   0xab,   0x25,
536   /*   \xc8   \xc9   \xca   \xcb   \xcc   \xcd   \xce   \xcf */
537      0x26,   0xac,   0x20,   0x48,   0x4a,   0x6a,   0x6c,   0x6c,
538   /*   \xd0   \xd1   \xd2   \xd3   \xd4   \xd5   \xd6   \xd7 */
539      0xad,   0xae,   0x23,   0x24,   0x2c,   0x2d,   0xaf,   0xb0,
540   /*   \xd8   \xd9   \xda   \xdb   \xdc   \xdd   \xde   \xdf */
541      0x80,   0xb1,   0xb2,   0xb3,   0xb4,   0xb5,   0xb6,   0xb7,
542   /*   \xe0   \xe1   \xe2   \xe3   \xe4   \xe5   \xe6   \xe7 */
543      0xb8,   0xb9,   0xba,   0xbb,   0xbc,   0xbd,   0xbe,   0xbf,
544   /*   \xe8   \xe9   \xea   \xeb   \xec   \xed   \xee   \xef */
545      0xc0,   0xc1,   0xc2,   0xc3,   0xc4,   0xc5,   0xc6,   0xc7,
546   /*   \xf0   \xf1   \xf2   \xf3   \xf4   \xf5   \xf6   \xf7 */
547      0xc8,   0xc9,   0xca,   0xcb,   0xcc,   0xcd,   0xce,   0xcf,
548   /*   \xf8   \xf9   \xfa   \xfb   \xfc   \xfd   \xfe   \xff */
549      0xd0,   0xd1,   0xd2,   0xd3,   0xd4,   0xd5,   0xd6,   0xd7
550   };
551
552   size_t common_len;
553   int i;
554   int c1, c2;
555
556   common_len = (s1[0] <= s2[0]) ? s1[0] : s2[0];
557
558   for (i=0; i<common_len; i++)
559   {
560      c1 = mac_char_sort_table[s1[i+1]];
561      c2 = mac_char_sort_table[s2[i+1]];
562      if (c1 != c2)
563         return c1 - c2;
564   }
565
566   return ((int)s1[0] - s2[0]);
567}
568
569/*
570   mac_strcpy()
571
572   Copy a macintosh string
573
574   dst (O): dest macintosh string
575   src (I): source macintosh string (first byte is length)
576
577   Return a zero if s1 and s2 are equal, a negative value if s1 is less than
578   s2, and a positive value if s1 is greater than s2.
579*/
580INLINE void mac_strcpy(UINT8 *dest, const UINT8 *src)
581{
582   memcpy(dest, src, src[0]+1);
583}
584
585#ifdef UNUSED_FUNCTION
586/*
587   mac_strncpy()
588
589   Copy a macintosh string
590
591   dst (O): dest macintosh string
592   n (I): max string length for dest (range 0-255, buffer length + 1)
593   src (I): source macintosh string (first byte is length)
594*/
595static void mac_strncpy(UINT8 *dest, int n, const UINT8 *src)
596{
597   size_t len;
598
599   len = src[0];
600   if (len > n)
601      len = n;
602   dest[0] = len;
603   memcpy(dest+1, src+1, len);
604}
605#endif
606
607/*
608   disk image reference
609*/
610typedef struct mac_l1_imgref
611{
612   imgtool_image *image;
613   UINT32 heads;
614} mac_l1_imgref;
615
616
617
618static imgtoolerr_t mac_find_block(mac_l1_imgref *image, int block,
619   UINT32 *track, UINT32 *head, UINT32 *sector)
620{
621   *track = 0;
622   while(block >= (apple35_sectors_per_track(imgtool_floppy(image->image), *track) * image->heads))
623   {
624      block -= (apple35_sectors_per_track(imgtool_floppy(image->image), (*track)++) * image->heads);
625      if (*track >= 80)
626         return IMGTOOLERR_SEEKERROR;
627   }
628
629   *head = block / apple35_sectors_per_track(imgtool_floppy(image->image), *track);
630   *sector = block % apple35_sectors_per_track(imgtool_floppy(image->image), *track);
631   return IMGTOOLERR_SUCCESS;
632}
633
634
635
636/*
637   image_read_block()
638
639   Read one 512-byte block of data from a macintosh disk image
640
641   image (I/O): level-1 image reference
642   block (I): address of block to read
643   dest (O): buffer where block data should be stored
644
645   Return imgtool error code
646*/
647static imgtoolerr_t image_read_block(mac_l1_imgref *image, UINT32 block, void *dest)
648{
649   imgtoolerr_t err;
650   floperr_t ferr;
651   UINT32 track, head, sector;
652
653   err = mac_find_block(image, block, &track, &head, &sector);
654   if (err)
655      return err;
656
657   ferr = floppy_read_sector(imgtool_floppy(image->image), head, track, sector, 0, dest, 512);
658   if (ferr)
659      return imgtool_floppy_error(ferr);
660
661   return IMGTOOLERR_SUCCESS;
662}
663
664/*
665   image_write_block()
666
667   Read one 512-byte block of data from a macintosh disk image
668
669   image (I/O): level-1 image reference
670   block (I): address of block to write
671   src (I): buffer with the block data
672
673   Return imgtool error code
674*/
675static imgtoolerr_t image_write_block(mac_l1_imgref *image, UINT32 block, const void *src)
676{
677   imgtoolerr_t err;
678   floperr_t ferr;
679   UINT32 track, head, sector;
680
681   err = mac_find_block(image, block, &track, &head, &sector);
682   if (err)
683      return err;
684
685   ferr = floppy_write_sector(imgtool_floppy(image->image), head, track, sector, 0, src, 512);
686   if (ferr)
687      return imgtool_floppy_error(ferr);
688
689   return IMGTOOLERR_SUCCESS;
690}
691
692/*
693   image_get_tag_len()
694
695   Get length of tag data (12 for GCR floppies, 20 for HD20, 0 otherwise)
696
697   image (I/O): level-1 image reference
698
699   Return tag length
700*/
701INLINE int image_get_tag_len(mac_l1_imgref *image)
702{
703   return 0;
704}
705
706
707
708/*
709   image_read_tag()
710
711   Read a 12- or 20-byte tag record associated with a disk block
712
713   image (I/O): level-1 image reference
714   block (I): address of block to read
715   dest (O): buffer where tag data should be stored
716
717   Return imgtool error code
718*/
719static imgtoolerr_t image_read_tag(mac_l1_imgref *image, UINT32 block, void *dest)
720{
721   return IMGTOOLERR_UNEXPECTED;
722}
723
724/*
725   image_write_tag()
726
727   Write a 12- or 20-byte tag record associated with a disk block
728
729   image (I/O): level-1 image reference
730   block (I): address of block to write
731   src (I): buffer with the tag data
732
733   Return imgtool error code
734*/
735static imgtoolerr_t image_write_tag(mac_l1_imgref *image, UINT32 block, const void *src)
736{
737   return IMGTOOLERR_UNEXPECTED;
738}
739
740#if 0
741#pragma mark -
742#pragma mark MFS/HFS WRAPPERS
743#endif
744
745typedef enum
746{
747   L2I_MFS,
748   L2I_HFS
749} mac_format;
750
751typedef enum { data_fork = 0x00, rsrc_fork = 0xff } mac_forkID;
752
753typedef struct mac_l2_imgref mac_l2_imgref;
754
755/*
756   MFS image ref
757*/
758typedef struct mfs_l2_imgref
759{
760   UINT16 dir_num_files;
761   UINT16 dir_start;
762   UINT16 dir_blk_len;
763
764   UINT16 ABStart;
765
766   mac_str27 volname;
767
768   unsigned char ABlink_dirty[13];   /* dirty flag for each disk block in the ABlink array */
769   UINT8 ABlink[6141];
770} mfs_l2_imgref;
771
772/*
773   HFS extent descriptor
774*/
775typedef struct hfs_extent
776{
777   UINT16BE stABN;         /* first allocation block */
778   UINT16BE numABlks;      /* number of allocation blocks */
779} hfs_extent;
780
781/*
782   HFS likes to group extents by 3 (it is 8 with HFS+), so we create a
783   specific type.
784*/
785typedef hfs_extent hfs_extent_3[3];
786
787/*
788   MFS open file ref
789*/
790typedef struct mfs_fileref
791{
792   UINT16 stBlk;               /* first allocation block of file */
793} mfs_fileref;
794
795/*
796   HFS open file ref
797*/
798typedef struct hfs_fileref
799{
800   hfs_extent_3 extents;         /* first 3 file extents */
801
802   UINT32 parID;               /* CNID of parent directory (undefined for extent & catalog files) */
803   mac_str31 filename;            /* file name (undefined for extent & catalog files) */
804} hfs_fileref;
805
806/*
807   MFS/HFS open file ref
808*/
809typedef struct mac_fileref
810{
811   mac_l2_imgref *l2_img;         /* image pointer */
812
813   UINT32 fileID;               /* file ID (a.k.a. CNID in HFS/HFS+) */
814
815   mac_forkID forkType;         /* 0x00 for data, 0xff for resource */
816
817   UINT32 eof;                  /* logical end-of-file */
818   UINT32 pLen;               /* physical end-of-file */
819
820   UINT32 crPs;               /* current position in file */
821
822   UINT8 reload_buf;
823   UINT8 block_buffer[512];      /* buffer with current file block */
824
825   union
826   {
827      mfs_fileref mfs;
828      hfs_fileref hfs;
829   } u;
830} mac_fileref;
831
832/*
833   open BT ref
834*/
835typedef struct mac_BTref
836{
837   mac_fileref fileref;   /* open B-tree file ref */
838
839   UINT16 nodeSize;      /* size of a node, in bytes */
840   UINT32 rootNode;      /* node number of root node */
841   UINT32 firstLeafNode;   /* node number of first leaf node */
842   UINT32 attributes;      /* persistent attributes about the tree */
843   UINT16 treeDepth;      /* maximum height (usually leaf nodes) */
844   UINT16 maxKeyLength;   /* maximum key length */
845
846   /* function to compare keys during tree searches */
847   int (*key_compare_func)(const void *key1, const void *key2);
848
849   void *node_buf;         /* current node buffer */
850} mac_BTref;
851
852/*
853   Constants for BTHeaderRec attributes field
854*/
855enum
856{
857   btha_badCloseMask         = 0x00000001,   /* reserved */
858   btha_bigKeysMask         = 0x00000002,   /* key length field is 16 bits */
859   btha_variableIndexKeysMask   = 0x00000004   /* keys in index nodes are variable length */
860};
861
862/*
863   HFS image ref
864*/
865typedef struct hfs_l2_imgref
866{
867   UINT16 VBM_start;
868
869   UINT16 ABStart;
870
871   mac_str27 volname;
872
873   mac_BTref extents_BT;
874   mac_BTref cat_BT;
875
876   UINT8 VBM[8192];
877} hfs_l2_imgref;
878
879/*
880   MFS/HFS image ref
881*/
882struct mac_l2_imgref
883{
884   mac_l1_imgref l1_img;
885
886   UINT16 numABs;
887   UINT16 blocksperAB;
888
889   UINT16 freeABs;
890
891   UINT32 nxtCNID;      /* nxtFNum in MFS, nxtCNID in HFS */
892
893   mac_format format;
894   union
895   {
896      mfs_l2_imgref mfs;
897      hfs_l2_imgref hfs;
898   } u;
899};
900
901/*
902   MFS Master Directory Block
903*/
904typedef struct mfs_mdb
905{
906   UINT8    sigWord[2];   /* volume signature - always $D2D7 */
907   UINT32BE crDate;      /* date and time of volume creation */
908   UINT32BE lsMod/*lsBkUp???*/;/* date and time of last modification (backup???) */
909   UINT16BE atrb;         /* volume attributes (0x0000) */
910                        /* bit 15 is set if volume is locked by software */
911   UINT16BE nmFls;         /* number of files in directory */
912   UINT16BE dirSt;         /* first block of directory */
913
914   UINT16BE blLn;         /* length of directory in blocks (0x000C) */
915   UINT16BE nmAlBlks;      /* number of allocation blocks in volume (0x0187) */
916   UINT32BE alBlkSiz;      /* size (in bytes) of allocation blocks (0x00000400) */
917   UINT32BE clpSiz;      /* default clump size - number of bytes to allocate
918                        when a file grows (0x00002000) */
919   UINT16BE alBlSt;      /* first allocation block in volume (0x0010) */
920
921   UINT32BE nxtFNum;      /* next unused file number */
922   UINT16BE freeABs;      /* number of unused allocation blocks */
923
924   mac_str27 VN;         /* volume name */
925
926   UINT8    ABlink[512-64];/* Link array for file ABs.  Array of nmAlBlks
927                     12-bit-long entries, indexed by AB address.  If an
928                     AB belongs to no file, the entry is 0; if an AB is
929                     the last in any file, the entry is 1; if an AB
930                     belongs to a file and is not the last one, the
931                     entry is the AB address of the next file AB plus 1.
932                     Note that the array extends on as many consecutive
933                     disk blocks as needed (usually the MDB block plus
934                     the next one).  Incidentally, this array is not
935                     saved in the secondary MDB: presumably, the idea
936                     was that the disk utility could rely on the tag
937                     data to rebuild the link array if it should ever
938                     be corrupted. */
939} mfs_mdb;
940
941/*
942   HFS Master Directory Block
943*/
944typedef struct hfs_mdb
945{
946/* First fields are similar to MFS, though several fields have a different meaning */
947   UINT8    sigWord[2];   /* volume signature - always $D2D7 */
948   UINT32BE crDate;      /* date and time of volume creation */
949   UINT32BE lsMod;         /* date and time of last modification */
950   UINT16BE atrb;         /* volume attributes (0x0000) */
951                        /* bit 15 is set if volume is locked by software */
952   UINT16BE nmFls;         /* number of files in root folder */
953   UINT16BE VBMSt;         /* first block of volume bitmap */
954   UINT16BE allocPtr;      /* start of next allocation search */
955
956   UINT16BE nmAlBlks;      /* number of allocation blocks in volume */
957   UINT32BE alBlkSiz;      /* size (in bytes) of allocation blocks */
958   UINT32BE clpSiz;      /* default clump size - number of bytes to allocate
959                        when a file grows */
960   UINT16BE alBlSt;      /* first allocation block in volume (0x0010) */
961   UINT32BE nxtCNID;      /* next unused catalog node ID */
962   UINT16BE freeABs;      /* number of unused allocation blocks */
963   mac_str27 VN;         /* volume name */
964
965/* next fields are HFS-specific */
966
967   UINT32BE volBkUp;      /* date and time of last backup */
968   UINT16BE vSeqNum;      /* volume backup sequence number */
969   UINT32BE wrCnt;         /* volume write count */
970   UINT32BE xtClpSiz;      /* clump size for extents overflow file */
971   UINT32BE ctClpSiz;      /* clump size for catalog file */
972   UINT16BE nmRtDirs;      /* number of directories in root folder */
973   UINT32BE filCnt;      /* number of files in volume */
974   UINT32BE dirCnt;      /* number of directories in volume */
975   UINT8    fndrInfo[32];   /* information used by the Finder */
976
977   union
978   {
979      struct
980      {
981         UINT16BE VCSize;      /* size (in blocks) of volume cache */
982         UINT16BE VBMCSize;      /* size (in blocks) of volume bitmap cache */
983         UINT16BE ctlCSize;      /* size (in blocks) of common volume cache */
984      } v1;
985      struct
986      {
987         UINT16BE embedSigWord;   /* embedded volume signature */
988         hfs_extent embedExtent;   /* embedded volume location and size */
989      } v2;
990   } u;
991
992   UINT32BE xtFlSize;      /* size (in bytes) of extents overflow file */
993   hfs_extent_3 xtExtRec;   /* extent record for extents overflow file */
994   UINT32BE ctFlSize;      /* size (in bytes) of catalog file */
995   hfs_extent_3 ctExtRec;   /* extent record for catalog file */
996} hfs_mdb;
997
998/* to save a little stack space, we use the same buffer for MDB and next blocks */
999typedef union img_open_buf
1000{
1001   mfs_mdb mfs_mdb;
1002   hfs_mdb hfs_mdb;
1003   UINT8 raw[512];
1004} img_open_buf;
1005
1006/*
1007   Information extracted from catalog/directory
1008*/
1009typedef struct mac_dirent
1010{
1011   UINT16 dataRecType;         /* type of data record */
1012
1013   mac_FInfo flFinderInfo;      /* information used by the Finder */
1014   mac_FXInfo flXFinderInfo;   /* information used by the Finder */
1015
1016   UINT8  flags;            /* bit 0=1 if file locked */
1017
1018   UINT32 fileID;            /* file ID in directory/catalog */
1019
1020   UINT32 dataLogicalSize;      /* logical EOF of data fork */
1021   UINT32 dataPhysicalSize;   /* physical EOF of data fork */
1022   UINT32 rsrcLogicalSize;      /* logical EOF of resource fork */
1023   UINT32 rsrcPhysicalSize;   /* physical EOF of resource fork */
1024
1025   UINT32 createDate;         /* date and time of creation */
1026   UINT32 modifyDate;         /* date and time of last modification */
1027} mac_dirent;
1028
1029/*
1030   Tag record for GCR floppies (12 bytes)
1031
1032   And, no, I don't know the format of the 20-byte tag record of the HD20
1033*/
1034typedef struct floppy_tag_record
1035{
1036   UINT32BE fileID;         /* a.k.a. CNID */
1037                        /* a value of 1 seems to be the default for non-AB blocks, but this is not consistent */
1038   UINT8 ftype;            /* bit 1 = 1 if resource fork */
1039                        /* bit 0 = 1 if block is allocated to user file (i.e. it is not
1040                           in HFS extent & catalog, and not in non-AB blocks such
1041                           as MDB and MFS directory)??? */
1042                        /* bit 7 seems to be used, but I don't know what it means */
1043                        /* a value of $FF seems to be the default for non-AB blocks, but this is not consistent */
1044   UINT8 fattr;            /* bit 0 = 1 if locked(?) */
1045                        /* a value of $FF seems to be the default for non-AB blocks, but this is not consistent */
1046   UINT16BE fblock;         /* relative file block number (enough for any volume up to 32 MBytes in size) */
1047   UINT32BE wrCnt;            /* MFS: date and time of last write */
1048                        /* HFS: seems related to the wrCnt field in the mdb, i.e.
1049                           each time a volume is written to, the current value of
1050                           wrCnt is written in the tag field, then it is incremented */
1051                        /* (DV17 says "disk block number", but it cannot be true) */
1052} floppy_tag_record;
1053
1054#ifdef UNUSED_FUNCTION
1055static void hfs_image_close(mac_l2_imgref *l2_img);
1056#endif
1057static imgtoolerr_t mfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address);
1058static imgtoolerr_t hfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address);
1059static imgtoolerr_t mfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, mac_str255 filename, mac_dirent *cat_info, int create_it);
1060static imgtoolerr_t hfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, UINT32 *parID, mac_str255 filename, mac_dirent *cat_info);
1061static imgtoolerr_t mfs_file_open(mac_l2_imgref *l2_img, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref);
1062static imgtoolerr_t hfs_file_open(mac_l2_imgref *l2_img, UINT32 parID, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref);
1063static imgtoolerr_t mfs_file_setABeof(mac_fileref *fileref, UINT32 newABeof);
1064static imgtoolerr_t mfs_dir_update(mac_fileref *fileref);
1065
1066static mac_l2_imgref *get_imgref(imgtool_image *img)
1067{
1068   return (mac_l2_imgref *) imgtool_floppy_extrabytes(img);
1069}
1070
1071
1072#ifdef UNUSED_FUNCTION
1073/*
1074   mac_image_close
1075
1076   Close a macintosh image.
1077
1078   l2_img (I/O): level-2 image reference
1079*/
1080static void mac_image_close(mac_l2_imgref *l2_img)
1081{
1082   switch (l2_img->format)
1083   {
1084   case L2I_MFS:
1085      break;
1086
1087   case L2I_HFS:
1088      hfs_image_close(l2_img);
1089      break;
1090   }
1091}
1092#endif
1093
1094/*
1095   mac_lookup_path
1096
1097   Resolve a file path, and translate it to a parID + filename pair that enables
1098   to do an efficient file search on a HFS volume (and an inefficient one on
1099   MFS, but it is not an issue as MFS volumes typically have a few dozens
1100   files, vs. possibly thousands with HFS volumes).
1101
1102   l2_img (I/O): level-2 image reference
1103   fpath (I): file path (C string)
1104   parID (O): set to the CNID of the parent directory if the volume is in HFS
1105      format (reserved for MFS volumes)
1106   filename (O): set to the actual name of the file, with capitalization matching
1107      the one on the volume rather than the one in the fpath parameter (Mac
1108      string)
1109   cat_info (O): catalog info for this file extracted from the catalog file
1110      (may be NULL)
1111
1112   Return imgtool error code
1113*/
1114static imgtoolerr_t mac_lookup_path(mac_l2_imgref *l2_img, const char *fpath, UINT32 *parID, mac_str255 filename, mac_dirent *cat_info, int create_it)
1115{
1116   imgtoolerr_t err = IMGTOOLERR_UNEXPECTED;
1117
1118   switch (l2_img->format)
1119   {
1120      case L2I_MFS:
1121         *parID = 0;
1122         err = mfs_lookup_path(l2_img, fpath, filename, cat_info, create_it);
1123         break;
1124
1125      case L2I_HFS:
1126         err = hfs_lookup_path(l2_img, fpath, parID, filename, cat_info);
1127         break;
1128   }
1129   return err;
1130}
1131
1132/*
1133   mac_file_open
1134
1135   Open a file located on a macintosh image
1136
1137   l2_img (I/O): level-2 image reference
1138   parID (I): CNID of the parent directory if the volume is in HFS format
1139      (reserved for MFS volumes)
1140   filename (I): name of the file (Mac string)
1141   mac_forkID (I): tells which fork should be opened
1142   fileref (O): mac file reference to open
1143
1144   Return imgtool error code
1145*/
1146static imgtoolerr_t mac_file_open(mac_l2_imgref *l2_img, UINT32 parID, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref)
1147{
1148   switch (l2_img->format)
1149   {
1150   case L2I_MFS:
1151      return mfs_file_open(l2_img, filename, fork, fileref);
1152
1153   case L2I_HFS:
1154      return hfs_file_open(l2_img, parID, filename, fork, fileref);
1155   }
1156
1157   return IMGTOOLERR_UNEXPECTED;
1158}
1159
1160/*
1161   mac_file_read
1162
1163   Read data from an open mac file, starting at current position in file
1164
1165   fileref (I/O): mac file reference
1166   len (I): number of bytes to read
1167   dest (O): destination buffer
1168
1169   Return imgtool error code
1170*/
1171static imgtoolerr_t mac_file_read(mac_fileref *fileref, UINT32 len, void *dest)
1172{
1173   UINT32 block = 0;
1174   floppy_tag_record tag;
1175   int run_len;
1176   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1177
1178   if ((fileref->crPs + len) > fileref->eof)
1179      /* EOF */
1180      return IMGTOOLERR_UNEXPECTED;
1181
1182   while (len > 0)
1183   {
1184      if (fileref->reload_buf)
1185      {
1186         switch (fileref->l2_img->format)
1187         {
1188         case L2I_MFS:
1189            err = mfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1190            break;
1191
1192         case L2I_HFS:
1193            err = hfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1194            break;
1195         }
1196         if (err)
1197            return err;
1198         err = image_read_block(&fileref->l2_img->l1_img, block, fileref->block_buffer);
1199         if (err)
1200            return err;
1201         fileref->reload_buf = FALSE;
1202
1203         if (TAG_EXTRA_CHECKS)
1204         {
1205            /* optional check */
1206            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
1207            {
1208               err = image_read_tag(&fileref->l2_img->l1_img, block, &tag);
1209               if (err)
1210                  return err;
1211
1212               if ((get_UINT32BE(tag.fileID) != fileref->fileID)
1213                  || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
1214                  || (get_UINT16BE(tag.fblock) != ((fileref->crPs/512) & 0xffff)))
1215               {
1216                  return IMGTOOLERR_CORRUPTIMAGE;
1217               }
1218            }
1219         }
1220      }
1221      run_len = 512 - (fileref->crPs % 512);
1222      if (run_len > len)
1223         run_len = len;
1224
1225      memcpy(dest, fileref->block_buffer+(fileref->crPs % 512), run_len);
1226      len -= run_len;
1227      dest = (UINT8 *)dest + run_len;
1228      fileref->crPs += run_len;
1229      if ((fileref->crPs % 512) == 0)
1230         fileref->reload_buf = TRUE;
1231   }
1232
1233   return IMGTOOLERR_SUCCESS;
1234}
1235
1236/*
1237   mac_file_write
1238
1239   Write data to an open mac file, starting at current position in file
1240
1241   fileref (I/O): mac file reference
1242   len (I): number of bytes to read
1243   dest (O): destination buffer
1244
1245   Return imgtool error code
1246*/
1247static imgtoolerr_t mac_file_write(mac_fileref *fileref, UINT32 len, const void *src)
1248{
1249   UINT32 block = 0;
1250   floppy_tag_record tag;
1251   int run_len;
1252   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1253
1254   if ((fileref->crPs + len) > fileref->eof)
1255      /* EOF */
1256      return IMGTOOLERR_UNEXPECTED;
1257
1258   while (len > 0)
1259   {
1260      switch (fileref->l2_img->format)
1261      {
1262      case L2I_MFS:
1263         err = mfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1264         break;
1265
1266      case L2I_HFS:
1267         err = hfs_file_get_nth_block_address(fileref, fileref->crPs/512, &block);
1268         break;
1269      }
1270      if (err)
1271         return err;
1272
1273      if (TAG_CHECKS)
1274      {
1275         /* optional check */
1276         if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
1277         {
1278            err = image_read_tag(&fileref->l2_img->l1_img, block, &tag);
1279            if (err)
1280               return err;
1281
1282            if ((get_UINT32BE(tag.fileID) != fileref->fileID)
1283               || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
1284               || (get_UINT16BE(tag.fblock) != ((fileref->crPs/512) & 0xffff)))
1285            {
1286               return IMGTOOLERR_CORRUPTIMAGE;
1287            }
1288         }
1289      }
1290
1291      if (fileref->reload_buf)
1292      {
1293         err = image_read_block(&fileref->l2_img->l1_img, block, fileref->block_buffer);
1294         if (err)
1295            return err;
1296         fileref->reload_buf = FALSE;
1297      }
1298      run_len = 512 - (fileref->crPs % 512);
1299      if (run_len > len)
1300         run_len = len;
1301
1302      memcpy(fileref->block_buffer+(fileref->crPs % 512), src, run_len);
1303      err = image_write_block(&fileref->l2_img->l1_img, block, fileref->block_buffer);
1304      if (err)
1305         return err;
1306      /* update tag data */
1307      if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
1308      {
1309         if (!TAG_CHECKS)
1310         {
1311            err = image_read_tag(&fileref->l2_img->l1_img, block, &tag);
1312            if (err)
1313               return err;
1314         }
1315
1316         switch (fileref->l2_img->format)
1317         {
1318         case L2I_MFS:
1319            set_UINT32BE(&tag.wrCnt, mac_time_now());
1320            break;
1321
1322         case L2I_HFS:
1323            /*set_UINT32BE(&tag.wrCnt, ++fileref->l2_img.u.hfs.wrCnt);*/   /* ***TODO*** */
1324            break;
1325         }
1326
1327         err = image_write_tag(&fileref->l2_img->l1_img, block, &tag);
1328         if (err)
1329            return err;
1330      }
1331      len -= run_len;
1332      src = (const UINT8 *)src + run_len;
1333      fileref->crPs += run_len;
1334      if ((fileref->crPs % 512) == 0)
1335         fileref->reload_buf = TRUE;
1336   }
1337
1338   return IMGTOOLERR_SUCCESS;
1339}
1340
1341#ifdef UNUSED_FUNCTION
1342/*
1343   mac_file_tell
1344
1345   Get current position in an open mac file
1346
1347   fileref (I/O): mac file reference
1348   filePos (O): current position in file
1349
1350   Return imgtool error code
1351*/
1352static imgtoolerr_t mac_file_tell(mac_fileref *fileref, UINT32 *filePos)
1353{
1354   *filePos = fileref->crPs;
1355
1356   return IMGTOOLERR_SUCCESS;
1357}
1358#endif
1359
1360/*
1361   mac_file_seek
1362
1363   Set current position in an open mac file
1364
1365   fileref (I/O): mac file reference
1366   filePos (I): new position in file
1367
1368   Return imgtool error code
1369*/
1370static imgtoolerr_t mac_file_seek(mac_fileref *fileref, UINT32 filePos)
1371{
1372   if ((fileref->crPs / 512) != (filePos / 512))
1373      fileref->reload_buf = TRUE;
1374
1375   fileref->crPs = filePos;
1376
1377   return IMGTOOLERR_SUCCESS;
1378}
1379
1380/*
1381   mac_file_seteof
1382
1383   Set the position of the EOF in an open mac file
1384
1385   fileref (I/O): mac file reference
1386   newEof (I): new position of EOF in file
1387
1388   Return imgtool error code
1389*/
1390static imgtoolerr_t mac_file_seteof(mac_fileref *fileref, UINT32 newEof)
1391{
1392   UINT32 newABEof;
1393   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1394
1395   newABEof = (newEof + fileref->l2_img->blocksperAB * 512 - 1) / (fileref->l2_img->blocksperAB * 512);
1396
1397   /*if (fileref->pLen % (fileref->l2_img->blocksperAB * 512))
1398      return IMGTOOLERR_CORRUPTIMAGE;*/
1399
1400   if (newEof < fileref->eof)
1401      fileref->eof = newEof;
1402
1403   switch (fileref->l2_img->format)
1404   {
1405   case L2I_MFS:
1406      err = mfs_file_setABeof(fileref, newABEof);
1407      break;
1408
1409   case L2I_HFS:
1410      err = IMGTOOLERR_UNIMPLEMENTED;
1411      break;
1412   }
1413   if (err)
1414      return err;
1415
1416   fileref->eof = newEof;
1417
1418   err = mfs_dir_update(fileref);
1419   if (err)
1420      return err;
1421
1422   /* update current pos if beyond new EOF */
1423   /*if (fileref->crPs > newEof)
1424   {
1425      if ((fileref->crPs / 512) != (newEof / 512))
1426         fileref->reload_buf = TRUE;
1427
1428      fileref->crPs = newEof;
1429   }*/
1430
1431   return IMGTOOLERR_SUCCESS;
1432}
1433
1434#if 0
1435#pragma mark -
1436#pragma mark MFS IMPLEMENTATION
1437#endif
1438
1439/*
1440   directory entry for use in the directory file
1441
1442   Note the structure is variable length.  It is always word-aligned, and
1443   cannot cross block boundaries.
1444
1445   Note that the directory does not seem to be sorted: the order in which
1446   files appear does not match file names, and it does not always match file
1447   IDs.
1448*/
1449typedef struct mfs_dir_entry
1450{
1451   UINT8    flags;            /* bit 7=1 if entry used, bit 0=1 if file locked */
1452                        /* 0x00 means end of block: if we are not done
1453                        with reading the directory, the remnants will
1454                        be read from next block */
1455   UINT8    flVersNum;         /* version number (usually 0x00, but I don't
1456                           have the IM volume that describes it) */
1457   mac_FInfo flFinderInfo;      /* information used by the Finder */
1458
1459   UINT32BE fileID;         /* file ID */
1460
1461   UINT16BE dataStartBlock;   /* first allocation block of data fork */
1462   UINT32BE dataLogicalSize;   /* logical EOF of data fork */
1463   UINT32BE dataPhysicalSize;   /* physical EOF of data fork */
1464   UINT16BE rsrcStartBlock;   /* first allocation block of resource fork */
1465   UINT32BE rsrcLogicalSize;   /* logical EOF of resource fork */
1466   UINT32BE rsrcPhysicalSize;   /* physical EOF of resource fork */
1467
1468   UINT32BE createDate;      /* date and time of creation */
1469   UINT32BE modifyDate;      /* date and time of last modification */
1470
1471   UINT8    name[1];         /* first char is length of file name */
1472                        /* next chars are file name - 255 chars at most */
1473                        /* IIRC, Finder 7 only supports 31 chars,
1474                        wheareas earlier versions support 63 chars */
1475} mfs_dir_entry;
1476
1477/*
1478   FOBJ desktop resource: describes a folder, or the location of the volume
1479   icon.
1480
1481   In typical Apple manner, this resource is not documented.  However, I have
1482   managed to reverse engineer some parts of it.
1483*/
1484typedef struct mfs_FOBJ
1485{
1486   UINT8 unknown0[2];      /* $00: $0004 for disk, $0008 for folder??? */
1487   mac_point location;      /* $02: location in parent window */
1488   UINT8 unknown1[4];      /* $06: ??? */
1489   UINT8 view;            /* $0A: manner in which folders are displayed??? */
1490   UINT8 unknown2;         /* $0B: ??? */
1491   UINT16BE par_fldr;      /* $0C: parent folder ID */
1492   UINT8 unknown3[10];      /* $0E: ??? */
1493   UINT16BE unknown4;      /* $18: ??? */
1494   UINT32BE createDate;   /* $1A: date and time of creation */
1495   UINT32BE modifyDate;   /* $1E: date and time of last modification */
1496   UINT16BE unknown5;      /* $22: put-away folder ID?????? */
1497   UINT8 unknown6[8];      /* $24: ??? */
1498   mac_rect bounds;      /* $2C: window bounds */
1499   mac_point scroll;      /* $34: current scroll offset??? */
1500   union
1501   {   /* I think there are two versions of the structure */
1502      struct
1503      {
1504         UINT16BE item_count;   /* number of items (folders and files) in
1505                              this folder */
1506         UINT32BE item_descs[1];   /* this variable-length array has
1507                              item_count entries - meaning of entry is unknown */
1508      } v1;
1509      struct
1510      {
1511         UINT16BE zerofill;      /* always 0? */
1512         UINT16BE unknown0;      /* always 0??? */
1513         UINT16BE item_count;   /* number of items (folders and files) in
1514                              this folder */
1515         UINT8 unknown1[20];      /* ??? */
1516         UINT8 name[1];         /* variable-length macintosh string */
1517      } v2;
1518   } u;
1519} mfs_FOBJ;
1520
1521/*
1522   MFS open dir ref
1523*/
1524typedef struct mfs_dirref
1525{
1526   mac_l2_imgref *l2_img;         /* image pointer */
1527   UINT16 index;               /* current file index in the disk directory */
1528   UINT16 cur_block;            /* current block offset in directory file */
1529   UINT16 cur_offset;            /* current byte offset in current block of directory file */
1530   UINT8 block_buffer[512];      /* buffer with current directory block */
1531} mfs_dirref;
1532
1533
1534
1535static imgtoolerr_t mfs_image_create(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
1536{
1537   imgtoolerr_t err;
1538   UINT8 buffer[512];
1539   UINT32 heads, tracks, sector_bytes, i;
1540   UINT32 total_disk_blocks, total_allocation_blocks, allocation_block_size;
1541   UINT32 free_allocation_blocks;
1542
1543   heads = option_resolution_lookup_int(opts, 'H');
1544   tracks = option_resolution_lookup_int(opts, 'T');
1545   sector_bytes = option_resolution_lookup_int(opts, 'L');
1546
1547   get_imgref(image)->l1_img.image = image;
1548   get_imgref(image)->l1_img.heads = heads;
1549
1550   if (sector_bytes != 512)
1551      return IMGTOOLERR_UNEXPECTED;
1552
1553   /* computation */
1554   allocation_block_size = 1024;
1555   total_disk_blocks = 0;
1556   for (i = 0; i < tracks; i++)
1557      total_disk_blocks += heads * apple35_sectors_per_track(imgtool_floppy(image), i) * sector_bytes / 512;
1558   total_allocation_blocks = total_disk_blocks / (allocation_block_size / 512);
1559   free_allocation_blocks = total_allocation_blocks - 3;
1560
1561   /* write master directory block */
1562   memset(buffer, 0, sizeof(buffer));
1563   place_integer_be(buffer,  0, 2, 0xd2d7);               /* signature */
1564   place_integer_be(buffer,  2, 4, mac_time_now());         /* creation date */
1565   place_integer_be(buffer,  6, 4, mac_time_now());         /* last modified date */
1566   place_integer_be(buffer, 10, 2, 0);                     /* volume attributes */
1567   place_integer_be(buffer, 12, 2, 0);                     /* number of files in directory */
1568   place_integer_be(buffer, 14, 2, 4);                     /* first block of directory */
1569   place_integer_be(buffer, 16, 2, 12);                  /* length of directory in blocks */
1570   place_integer_be(buffer, 18, 2, total_allocation_blocks);   /* allocation blocks on volume count */
1571   place_integer_be(buffer, 20, 4, allocation_block_size);      /* allocation block size */
1572   place_integer_be(buffer, 24, 4, 8192);                  /* default clumping size */
1573   place_integer_be(buffer, 28, 2, 16);                  /* first allocation block on volume */
1574   place_integer_be(buffer, 30, 4, 2);                     /* next unused catalog node */
1575   place_integer_be(buffer, 34, 2, free_allocation_blocks);   /* free allocation block count */
1576   pascal_from_c_string(&buffer[36], 28, "Untitled");         /* volume title */
1577
1578   err = image_write_block(&get_imgref(image)->l1_img, 2, buffer);
1579   if (err)
1580      return err;
1581
1582   return IMGTOOLERR_SUCCESS;
1583}
1584
1585
1586
1587/*
1588   mfs_image_open
1589
1590   Open a MFS image.  Image must already be open on level 1.  This function
1591   should not be called directly: call mac_image_open() instead.
1592
1593   l2_img (I/O): level-2 image reference to open (l1_img and format fields
1594      must be initialized)
1595   img_open_buf (I): buffer with the MDB block
1596
1597   Return imgtool error code
1598*/
1599static imgtoolerr_t mfs_image_open(imgtool_image *image, imgtool_stream *stream)
1600{
1601   imgtoolerr_t err;
1602   mac_l2_imgref *l2_img;
1603   img_open_buf buf_local;
1604   img_open_buf *buf;
1605
1606   l2_img = get_imgref(image);
1607   l2_img->l1_img.image = image;
1608   l2_img->l1_img.heads = 1;
1609   l2_img->format = L2I_MFS;
1610
1611   /* read MDB */
1612   err = image_read_block(&l2_img->l1_img, 2, &buf_local.raw);
1613   if (err)
1614      return err;
1615   buf = &buf_local;
1616
1617   /* check signature word */
1618   if ((buf->mfs_mdb.sigWord[0] != 0xd2) || (buf->mfs_mdb.sigWord[1] != 0xd7)
1619         || (buf->mfs_mdb.VN[0] > 27))
1620      return IMGTOOLERR_CORRUPTIMAGE;
1621
1622   l2_img->u.mfs.dir_num_files = get_UINT16BE(buf->mfs_mdb.nmFls);
1623   l2_img->u.mfs.dir_start = get_UINT16BE(buf->mfs_mdb.dirSt);
1624   l2_img->u.mfs.dir_blk_len = get_UINT16BE(buf->mfs_mdb.blLn);
1625
1626   l2_img->numABs = get_UINT16BE(buf->mfs_mdb.nmAlBlks);
1627   if ((get_UINT32BE(buf->mfs_mdb.alBlkSiz) % 512) || (get_UINT32BE(buf->mfs_mdb.alBlkSiz) == 0))
1628      return IMGTOOLERR_CORRUPTIMAGE;
1629   l2_img->blocksperAB = get_UINT32BE(buf->mfs_mdb.alBlkSiz) / 512;
1630   l2_img->u.mfs.ABStart = get_UINT16BE(buf->mfs_mdb.alBlSt);
1631
1632   l2_img->nxtCNID = get_UINT32BE(buf->mfs_mdb.nxtFNum);
1633
1634   l2_img->freeABs = get_UINT16BE(buf->mfs_mdb.freeABs);
1635
1636   mac_strcpy(l2_img->u.mfs.volname, buf->mfs_mdb.VN);
1637
1638   if (l2_img->numABs > 4094)
1639      return IMGTOOLERR_CORRUPTIMAGE;
1640
1641   /* extract link array */
1642   {
1643      int byte_len = l2_img->numABs + ((l2_img->numABs + 1) >> 1);
1644      int cur_byte;
1645      int cur_block;
1646      int block_len = sizeof(buf->mfs_mdb.ABlink);
1647
1648      /* clear dirty flags */
1649      for (cur_block=0; cur_block<13; cur_block++)
1650         l2_img->u.mfs.ABlink_dirty[cur_block] = 0;
1651
1652      /* append the chunk after MDB to link array */
1653      cur_byte = 0;
1654      if (block_len > (byte_len - cur_byte))
1655         block_len = byte_len - cur_byte;
1656      memcpy(l2_img->u.mfs.ABlink+cur_byte, buf->mfs_mdb.ABlink, block_len);
1657      cur_byte += block_len;
1658      cur_block = 2;
1659      while (cur_byte < byte_len)
1660      {
1661         /* read next block */
1662         cur_block++;
1663         err = image_read_block(&l2_img->l1_img, cur_block, buf->raw);
1664         if (err)
1665            return err;
1666         block_len = 512;
1667
1668         /* append this block to link array */
1669         if (block_len > (byte_len - cur_byte))
1670            block_len = byte_len - cur_byte;
1671         memcpy(l2_img->u.mfs.ABlink+cur_byte, buf->raw, block_len);
1672         cur_byte += block_len;
1673      }
1674      /* check that link array and directory don't overlap */
1675      if (cur_block >= l2_img->u.mfs.dir_start)
1676         return IMGTOOLERR_CORRUPTIMAGE;
1677   }
1678
1679   return IMGTOOLERR_SUCCESS;
1680}
1681
1682/*
1683   mfs_update_mdb
1684
1685   Update MDB on disk
1686
1687   l2_img (I/O): level-2 image reference
1688
1689   Return imgtool error code
1690*/
1691static imgtoolerr_t mfs_update_mdb(mac_l2_imgref *l2_img)
1692{
1693   imgtoolerr_t err;
1694   union
1695   {
1696      mfs_mdb mfs_mdb;
1697      UINT8 raw[512];
1698   } buf;
1699
1700   assert(l2_img->format == L2I_MFS);
1701
1702   /* read MDB */
1703   err = image_read_block(&l2_img->l1_img, 2, &buf.mfs_mdb);
1704   if (err)
1705      return err;
1706
1707   set_UINT16BE(&buf.mfs_mdb.nmFls, l2_img->u.mfs.dir_num_files);
1708#if 0   /* these fields are never changed */
1709   set_UINT16BE(&buf.mfs_mdb.dirSt, l2_img->u.mfs.dir_start);
1710   set_UINT16BE(&buf.mfs_mdb.blLn, l2_img->u.mfs.dir_blk_len);
1711
1712   set_UINT16BE(&buf.mfs_mdb.nmAlBlks, l2_img->numABs);
1713   set_UINT32BE(&buf.mfs_mdb.alBlkSiz, l2_img->blocksperAB*512);
1714   set_UINT16BE(&buf.mfs_mdb.alBlSt, l2_img->u.mfs.ABStart);
1715#endif
1716
1717   set_UINT32BE(&buf.mfs_mdb.nxtFNum, l2_img->nxtCNID);
1718
1719   set_UINT16BE(&buf.mfs_mdb.freeABs, l2_img->freeABs);
1720
1721#if 0   /* these fields are never changed */
1722   mac_strcpy(buf.mfs_mdb.VN, l2_img->u.mfs.volname);
1723#endif
1724
1725   /* save link array */
1726   {
1727      int byte_len = l2_img->numABs + ((l2_img->numABs + 1) >> 1);
1728      int cur_byte = 0;
1729      int cur_block = 2;
1730      int block_len = sizeof(buf.mfs_mdb.ABlink);
1731
1732      /* update the chunk of link array after the MDB */
1733      if (block_len > (byte_len - cur_byte))
1734         block_len = byte_len - cur_byte;
1735      memcpy(buf.mfs_mdb.ABlink, l2_img->u.mfs.ABlink+cur_byte, block_len);
1736      cur_byte += block_len;
1737
1738      if (block_len < sizeof(buf.mfs_mdb.ABlink))
1739         memset(buf.mfs_mdb.ABlink+block_len, 0, sizeof(buf.mfs_mdb.ABlink)-block_len);
1740
1741      l2_img->u.mfs.ABlink_dirty[0] = 0;
1742
1743      /* write back modified MDB+link */
1744      err = image_write_block(&l2_img->l1_img, 2, &buf.mfs_mdb);
1745      if (err)
1746         return err;
1747
1748      while (cur_byte < byte_len)
1749      {
1750         /* advance to next block */
1751         cur_block++;
1752         block_len = 512;
1753
1754         /* extract the current chunk of link array */
1755         if (block_len > (byte_len - cur_byte))
1756            block_len = byte_len - cur_byte;
1757
1758         if (l2_img->u.mfs.ABlink_dirty[cur_block-2])
1759         {
1760            memcpy(buf.raw, l2_img->u.mfs.ABlink+cur_byte, block_len);
1761            if (block_len < 512)
1762               memset(buf.raw+block_len, 0, 512-block_len);
1763            /* write back link array */
1764            err = image_write_block(&l2_img->l1_img, cur_block, buf.raw);
1765            if (err)
1766               return err;
1767            l2_img->u.mfs.ABlink_dirty[cur_block-2] = 0;
1768         }
1769
1770         cur_byte += block_len;
1771      }
1772   }
1773
1774   return IMGTOOLERR_SUCCESS;
1775}
1776
1777/*
1778   mfs_dir_open
1779
1780   Open the directory file
1781
1782   l2_img (I/O): level-2 image reference
1783   dirref (O): open directory file reference
1784
1785   Return imgtool error code
1786*/
1787static imgtoolerr_t mfs_dir_open(mac_l2_imgref *l2_img, const char *path, mfs_dirref *dirref)
1788{
1789   imgtoolerr_t err;
1790
1791   assert(l2_img->format == L2I_MFS);
1792
1793   if (path[0])
1794      return IMGTOOLERR_PATHNOTFOUND;
1795
1796   dirref->l2_img = l2_img;
1797   dirref->index = 0;
1798
1799   dirref->cur_block = 0;
1800   dirref->cur_offset = 0;
1801   err = image_read_block(&l2_img->l1_img, l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1802   if (err)
1803      return err;
1804
1805   return IMGTOOLERR_SUCCESS;
1806}
1807
1808/*
1809   mfs_dir_read
1810
1811   Read one entry of directory file
1812
1813   dirref (I/O): open directory file reference
1814   dir_entry (O): set to point to the entry read: set to NULL if EOF or error
1815
1816   Return imgtool error code
1817*/
1818static imgtoolerr_t mfs_dir_read(mfs_dirref *dirref, mfs_dir_entry **dir_entry)
1819{
1820   mfs_dir_entry *cur_dir_entry;
1821   size_t cur_dir_entry_len;
1822   imgtoolerr_t err;
1823
1824
1825   if (dir_entry)
1826      *dir_entry = NULL;
1827
1828   if (dirref->index == dirref->l2_img->u.mfs.dir_num_files)
1829      /* EOF */
1830      return IMGTOOLERR_SUCCESS;
1831
1832   /* get cat entry pointer */
1833   cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1834   while ((dirref->cur_offset == 512) || ! (cur_dir_entry->flags & 0x80))
1835   {
1836      dirref->cur_block++;
1837      dirref->cur_offset = 0;
1838      if (dirref->cur_block > dirref->l2_img->u.mfs.dir_blk_len)
1839         /* aargh! */
1840         return IMGTOOLERR_CORRUPTIMAGE;
1841      err = image_read_block(&dirref->l2_img->l1_img, dirref->l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1842      if (err)
1843         return err;
1844      cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1845   }
1846
1847   cur_dir_entry_len = offsetof(mfs_dir_entry, name) + cur_dir_entry->name[0] + 1;
1848
1849   if ((dirref->cur_offset + cur_dir_entry_len) > 512)
1850      /* aargh! */
1851      return IMGTOOLERR_CORRUPTIMAGE;
1852
1853   /* entry looks valid: set pointer to entry */
1854   if (dir_entry)
1855      *dir_entry = cur_dir_entry;
1856
1857   /* update offset in block */
1858   dirref->cur_offset += cur_dir_entry_len;
1859   /* align to word boundary */
1860   dirref->cur_offset = (dirref->cur_offset + 1) & ~1;
1861
1862   /* update file count */
1863   dirref->index++;
1864
1865   return IMGTOOLERR_SUCCESS;
1866}
1867
1868/*
1869   mfs_dir_insert
1870
1871   Add an entry in the directory file
1872
1873   l2_img (I/O): level-2 image reference
1874   dirref (I/O): open directory file reference
1875   filename (I): name of the file for which an entry is created (Mac string)
1876   dir_entry (O): set to point to the created entry: set to NULL if EOF or
1877      error
1878
1879   Return imgtool error code
1880*/
1881static imgtoolerr_t mfs_dir_insert(mac_l2_imgref *l2_img, mfs_dirref *dirref, const UINT8 *new_fname, mfs_dir_entry **dir_entry)
1882{
1883   size_t new_dir_entry_len;
1884   mfs_dir_entry *cur_dir_entry;
1885   size_t cur_dir_entry_len;
1886   UINT32 cur_date;
1887   imgtoolerr_t err;
1888
1889   dirref->l2_img = l2_img;
1890   dirref->index = 0;
1891
1892   new_dir_entry_len = offsetof(mfs_dir_entry, name) + new_fname[0] + 1;
1893
1894   for (dirref->cur_block = 0; dirref->cur_block < dirref->l2_img->u.mfs.dir_blk_len; dirref->cur_block++)
1895   {
1896      /* read current block */
1897      err = image_read_block(&dirref->l2_img->l1_img, dirref->l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1898      if (err)
1899         return err;
1900
1901      /* get free chunk in this block */
1902      dirref->cur_offset = 0;
1903      cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1904      while ((dirref->cur_offset < 512) && (cur_dir_entry->flags & 0x80))
1905      {   /* skip cur_dir_entry */
1906         cur_dir_entry_len = offsetof(mfs_dir_entry, name) + cur_dir_entry->name[0] + 1;
1907         /* update offset in block */
1908         dirref->cur_offset += cur_dir_entry_len;
1909         /* align to word boundary */
1910         dirref->cur_offset = (dirref->cur_offset + 1) & ~1;
1911         /* update entry pointer */
1912         cur_dir_entry = (mfs_dir_entry *) (dirref->block_buffer + dirref->cur_offset);
1913         /* update file index (useless, but can't harm) */
1914         dirref->index++;
1915      }
1916
1917      if (new_dir_entry_len <= (/*512*/510 - dirref->cur_offset))
1918      {
1919         /*memcpy(cur_dir_entry, new_dir_entry, new_dir_entry_len);*/
1920         cur_dir_entry->flags = 0x80;
1921         cur_dir_entry->flVersNum = 0x00;
1922         memset(&cur_dir_entry->flFinderInfo, 0, sizeof(cur_dir_entry->flFinderInfo));
1923         set_UINT32BE(&cur_dir_entry->fileID, dirref->l2_img->nxtCNID++);
1924         set_UINT16BE(&cur_dir_entry->dataStartBlock, 1);
1925         set_UINT32BE(&cur_dir_entry->dataLogicalSize, 0);
1926         set_UINT32BE(&cur_dir_entry->dataPhysicalSize, 0);
1927         set_UINT16BE(&cur_dir_entry->rsrcStartBlock, 1);
1928         set_UINT32BE(&cur_dir_entry->rsrcLogicalSize, 0);
1929         set_UINT32BE(&cur_dir_entry->rsrcPhysicalSize, 0);
1930         cur_date = mac_time_now();
1931         set_UINT32BE(&cur_dir_entry->createDate, cur_date);
1932         set_UINT32BE(&cur_dir_entry->modifyDate, cur_date);
1933         mac_strcpy(cur_dir_entry->name, new_fname);
1934
1935         /* update offset in block */
1936         dirref->cur_offset += new_dir_entry_len;
1937         /* align to word boundary */
1938         dirref->cur_offset = (dirref->cur_offset + 1) & ~1;
1939         if (dirref->cur_offset < 512)
1940            /* mark remaining space as free record */
1941            dirref->block_buffer[dirref->cur_offset] = 0;
1942         /* write back directory */
1943         err = image_write_block(&dirref->l2_img->l1_img, dirref->l2_img->u.mfs.dir_start + dirref->cur_block, dirref->block_buffer);
1944         if (err)
1945            return err;
1946         /* update file count */
1947         dirref->l2_img->u.mfs.dir_num_files++;
1948
1949         /* update MDB (nxtCNID & dir_num_files fields) */
1950         err = mfs_update_mdb(dirref->l2_img);
1951         if (err)
1952            return err;
1953
1954         if (dir_entry)
1955            *dir_entry = cur_dir_entry;
1956         return IMGTOOLERR_SUCCESS;
1957      }
1958   }
1959
1960   return IMGTOOLERR_NOSPACE;
1961}
1962
1963/*
1964   mfs_dir_update
1965
1966   Update one entry of directory file
1967
1968   fileref (I/O): open file reference
1969
1970   Return imgtool error code
1971*/
1972static imgtoolerr_t mfs_dir_update(mac_fileref *fileref)
1973{
1974   UINT16 cur_block;
1975   UINT16 cur_offset;
1976   UINT8 block_buffer[512];
1977   mfs_dir_entry *cur_dir_entry;
1978   size_t cur_dir_entry_len;
1979   imgtoolerr_t err;
1980
1981   for (cur_block = 0; cur_block < fileref->l2_img->u.mfs.dir_blk_len; cur_block++)
1982   {
1983      /* read current block */
1984      err = image_read_block(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.dir_start + cur_block, block_buffer);
1985      if (err)
1986         return err;
1987
1988      /* get free chunk in this block */
1989      cur_offset = 0;
1990      cur_dir_entry = (mfs_dir_entry *) (block_buffer + cur_offset);
1991      while ((cur_offset < 512) && (cur_dir_entry->flags & 0x80))
1992      {
1993         if (get_UINT32BE(cur_dir_entry->fileID) == fileref->fileID)
1994         {   /* found it: update directory entry */
1995            switch (fileref->forkType)
1996            {
1997            case data_fork:
1998               set_UINT16BE(&cur_dir_entry->dataStartBlock, fileref->u.mfs.stBlk);
1999               set_UINT32BE(&cur_dir_entry->dataLogicalSize, fileref->eof);
2000               set_UINT32BE(&cur_dir_entry->dataPhysicalSize, fileref->pLen);
2001               break;
2002
2003            case rsrc_fork:
2004               set_UINT16BE(&cur_dir_entry->rsrcStartBlock, fileref->u.mfs.stBlk);
2005               set_UINT32BE(&cur_dir_entry->rsrcLogicalSize, fileref->eof);
2006               set_UINT32BE(&cur_dir_entry->rsrcPhysicalSize, fileref->pLen);
2007               break;
2008            }
2009            /* write back directory */
2010            err = image_write_block(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.dir_start + cur_block, block_buffer);
2011            if (err)
2012               return err;
2013
2014            return IMGTOOLERR_SUCCESS;
2015         }
2016         /* skip cur_dir_entry */
2017         cur_dir_entry_len = offsetof(mfs_dir_entry, name) + cur_dir_entry->name[0] + 1;
2018         /* update offset in block */
2019         cur_offset += cur_dir_entry_len;
2020         /* align to word boundary */
2021         cur_offset = (cur_offset + 1) & ~1;
2022         /* update entry pointer */
2023         cur_dir_entry = (mfs_dir_entry *) (block_buffer + cur_offset);
2024      }
2025   }
2026
2027   return IMGTOOLERR_UNEXPECTED;
2028}
2029
2030
2031/*
2032   mfs_find_dir_entry
2033
2034   Find a file in an MFS directory
2035
2036   dirref (I/O): open directory file reference
2037   filename (I): file name (Mac string)
2038   dir_entry (O): set to point to the entry read: set to NULL if EOF or error
2039
2040   Return imgtool error code
2041*/
2042static imgtoolerr_t mfs_find_dir_entry(mfs_dirref *dirref, const mac_str255 filename, mfs_dir_entry **dir_entry)
2043{
2044   mfs_dir_entry *cur_dir_entry;
2045   imgtoolerr_t err;
2046
2047   if (dir_entry)
2048      *dir_entry = NULL;
2049
2050   /*  scan dir for file */
2051   while (1)
2052   {
2053      err = mfs_dir_read(dirref, &cur_dir_entry);
2054      if (err)
2055         return err;
2056      if (!cur_dir_entry)
2057         /* EOF */
2058         break;
2059      if ((! mac_stricmp(filename, cur_dir_entry->name)) && (cur_dir_entry->flVersNum == 0))
2060      {   /* file found */
2061
2062         if (dir_entry)
2063            *dir_entry = cur_dir_entry;
2064
2065         return IMGTOOLERR_SUCCESS;
2066      }
2067   }
2068
2069   return IMGTOOLERR_FILENOTFOUND;
2070}
2071
2072/*
2073   mfs_lookup_path
2074
2075   Resolve a file path for MFS volumes.  This function should not be called
2076   directly: call mac_lookup_path instead.
2077
2078   l2_img (I/O): level-2 image reference
2079   fpath (I): file path (C string)
2080   filename (O): set to the actual name of the file, with capitalization matching
2081      the one on the volume rather than the one in the fpath parameter (Mac
2082      string)
2083   cat_info (I/O): on output, catalog info for this file extracted from the
2084      catalog file (may be NULL)
2085      If create_it is TRUE, created info will first be set according to the
2086      data from cat_info
2087   create_it (I): TRUE if entry should be created if not found
2088
2089   Return imgtool error code
2090*/
2091static imgtoolerr_t mfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, mac_str255 filename, mac_dirent *cat_info, int create_it)
2092{
2093   mfs_dirref dirref;
2094   mfs_dir_entry *dir_entry;
2095   imgtoolerr_t err;
2096
2097   /* rapid check */
2098   if (strchr(fpath, ':'))
2099      return IMGTOOLERR_BADFILENAME;
2100
2101   /* extract file name */
2102   c_to_mac_strncpy(filename, fpath, strlen(fpath));
2103
2104   /* open dir */
2105   mfs_dir_open(l2_img, "", &dirref);
2106
2107   /* find file */
2108   err = mfs_find_dir_entry(&dirref, filename, &dir_entry);
2109   if ((err == IMGTOOLERR_FILENOTFOUND) && create_it)
2110      err = mfs_dir_insert(l2_img, &dirref, filename, &dir_entry);
2111   if (err)
2112      return err;
2113
2114   mac_strcpy(filename, dir_entry->name);
2115
2116   if (create_it && cat_info)
2117   {
2118      dir_entry->flFinderInfo = cat_info->flFinderInfo;
2119      dir_entry->flags = (dir_entry->flags & 0x80) | (cat_info->flags & 0x7f);
2120      set_UINT32BE(&dir_entry->createDate, cat_info->createDate);
2121      set_UINT32BE(&dir_entry->modifyDate, cat_info->modifyDate);
2122
2123      /* write current directory block */
2124      err = image_write_block(&l2_img->l1_img, l2_img->u.mfs.dir_start + dirref.cur_block, dirref.block_buffer);
2125      if (err)
2126         return err;
2127   }
2128
2129   if (cat_info)
2130   {
2131      cat_info->flFinderInfo = dir_entry->flFinderInfo;
2132      memset(&cat_info->flXFinderInfo, 0, sizeof(cat_info->flXFinderInfo));
2133      cat_info->flags = dir_entry->flags;
2134      cat_info->fileID = get_UINT32BE(dir_entry->fileID);
2135      cat_info->dataLogicalSize = get_UINT32BE(dir_entry->dataLogicalSize);
2136      cat_info->dataPhysicalSize = get_UINT32BE(dir_entry->dataPhysicalSize);
2137      cat_info->rsrcLogicalSize = get_UINT32BE(dir_entry->rsrcLogicalSize);
2138      cat_info->rsrcPhysicalSize = get_UINT32BE(dir_entry->rsrcPhysicalSize);
2139      cat_info->createDate = get_UINT32BE(dir_entry->createDate);
2140      cat_info->modifyDate = get_UINT32BE(dir_entry->modifyDate);
2141      cat_info->dataRecType = 0x200; /* hcrt_File */
2142   }
2143
2144   return IMGTOOLERR_SUCCESS;
2145}
2146
2147/*
2148   mfs_file_open_internal
2149
2150   Open a file fork, given its directory entry.  This function should not be
2151   called directly: call mfs_file_open instead.
2152
2153   l2_img (I/O): level-2 image reference
2154   dir_entry (I): directory entry for the file to open
2155   mac_forkID (I): tells which fork should be opened
2156   fileref (O): mac file reference to open
2157
2158   Return imgtool error code
2159*/
2160static imgtoolerr_t mfs_file_open_internal(mac_l2_imgref *l2_img, const mfs_dir_entry *dir_entry, mac_forkID fork, mac_fileref *fileref)
2161{
2162   assert(l2_img->format == L2I_MFS);
2163
2164   fileref->l2_img = l2_img;
2165
2166   fileref->fileID = get_UINT32BE(dir_entry->fileID);
2167   fileref->forkType = fork;
2168
2169   switch (fork)
2170   {
2171   case data_fork:
2172      fileref->u.mfs.stBlk = get_UINT16BE(dir_entry->dataStartBlock);
2173      fileref->eof = get_UINT32BE(dir_entry->dataLogicalSize);
2174      fileref->pLen = get_UINT32BE(dir_entry->dataPhysicalSize);
2175      break;
2176
2177   case rsrc_fork:
2178      fileref->u.mfs.stBlk = get_UINT16BE(dir_entry->rsrcStartBlock);
2179      fileref->eof = get_UINT32BE(dir_entry->rsrcLogicalSize);
2180      fileref->pLen = get_UINT32BE(dir_entry->rsrcPhysicalSize);
2181      break;
2182   }
2183
2184   fileref->crPs = 0;
2185
2186   fileref->reload_buf = TRUE;
2187
2188   return IMGTOOLERR_SUCCESS;
2189}
2190
2191/*
2192   mfs_file_open
2193
2194   Open a file located on a MFS volume.  This function should not be called
2195   directly: call mac_file_open instead.
2196
2197   l2_img (I/O): level-2 image reference
2198   filename (I): name of the file (Mac string)
2199   mac_forkID (I): tells which fork should be opened
2200   fileref (O): mac file reference to open
2201
2202   Return imgtool error code
2203*/
2204static imgtoolerr_t mfs_file_open(mac_l2_imgref *l2_img, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref)
2205{
2206   mfs_dirref dirref;
2207   mfs_dir_entry *dir_entry;
2208   imgtoolerr_t err;
2209
2210   /* open dir */
2211   mfs_dir_open(l2_img, "", &dirref);
2212
2213   /* find file */
2214   err = mfs_find_dir_entry(&dirref, filename, &dir_entry);
2215   if (err)
2216      return err;
2217
2218   /* open it */
2219   return mfs_file_open_internal(l2_img, dir_entry, fork, fileref);
2220}
2221
2222/*
2223   mfs_get_ABlink
2224
2225   Read one entry of the Allocation Bitmap link array, on an MFS volume.
2226
2227   l2_img (I/O): level-2 image reference
2228   AB_address (I): index in the array, which is an AB address
2229
2230   Returns the 12-bit value read in array.
2231*/
2232static UINT16 mfs_get_ABlink(mac_l2_imgref *l2_img, UINT16 AB_address)
2233{
2234   UINT16 reply;
2235   int base;
2236
2237   assert(l2_img->format == L2I_MFS);
2238
2239   base = (AB_address >> 1) * 3;
2240
2241   if (! (AB_address & 1))
2242      reply = (l2_img->u.mfs.ABlink[base] << 4) | ((l2_img->u.mfs.ABlink[base+1] >> 4) & 0x0f);
2243   else
2244      reply = ((l2_img->u.mfs.ABlink[base+1] << 8) & 0xf00) | l2_img->u.mfs.ABlink[base+2];
2245
2246   return reply;
2247}
2248
2249/*
2250   mfs_set_ABlink
2251
2252   Set one entry of the Allocation Bitmap link array, on an MFS volume.
2253
2254   l2_img (I/O): level-2 image reference
2255   AB_address (I): index in the array, which is an AB address
2256   data (I): 12-bit value to write in array
2257*/
2258static void mfs_set_ABlink(mac_l2_imgref *l2_img, UINT16 AB_address, UINT16 data)
2259{
2260   int base;
2261
2262   assert(l2_img->format == L2I_MFS);
2263
2264   base = (AB_address >> 1) * 3;
2265
2266   if (! (AB_address & 1))
2267   {
2268      l2_img->u.mfs.ABlink[base] = (data >> 4) & 0xff;
2269      l2_img->u.mfs.ABlink[base+1] = (l2_img->u.mfs.ABlink[base+1] & 0x0f) | ((data << 4) & 0xf0);
2270
2271      l2_img->u.mfs.ABlink_dirty[(base+64)/512] = 1;
2272      l2_img->u.mfs.ABlink_dirty[(base+1+64)/512] = 1;
2273   }
2274   else
2275   {
2276      l2_img->u.mfs.ABlink[base+1] = (l2_img->u.mfs.ABlink[base+1] & 0xf0) | ((data >> 8) & 0x0f);
2277      l2_img->u.mfs.ABlink[base+2] = data & 0xff;
2278
2279      l2_img->u.mfs.ABlink_dirty[(base+1+64)/512] = 1;
2280      l2_img->u.mfs.ABlink_dirty[(base+2+64)/512] = 1;
2281   }
2282}
2283
2284/*
2285   mfs_file_get_nth_block_address
2286
2287   Get the disk block address of a given block in an open file on a MFS image.
2288   Called by macintosh file code.
2289
2290   fileref (I/O): open mac file reference
2291   block_num (I): file block index
2292   block_address (O): disk block address for the file block
2293
2294   Return imgtool error code
2295*/
2296static imgtoolerr_t mfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address)
2297{
2298   UINT32 AB_num;
2299   UINT32 i;
2300   UINT16 AB_address;
2301
2302   assert(fileref->l2_img->format == L2I_MFS);
2303
2304   AB_num = block_num / fileref->l2_img->blocksperAB;
2305
2306   AB_address = fileref->u.mfs.stBlk;
2307   if ((AB_address == 0) || (AB_address >= fileref->l2_img->numABs+2))
2308      /* 0 -> ??? */
2309      return IMGTOOLERR_CORRUPTIMAGE;
2310   if (AB_address == 1)
2311      /* EOF */
2312      return IMGTOOLERR_UNEXPECTED;
2313   AB_address -= 2;
2314   for (i=0; i<AB_num; i++)
2315   {
2316      AB_address = mfs_get_ABlink(fileref->l2_img, AB_address);
2317      if ((AB_address == 0) || (AB_address >= fileref->l2_img->numABs+2))
2318         /* 0 -> empty block: there is no way an empty block could make it
2319         into the link chain!!! */
2320         return IMGTOOLERR_CORRUPTIMAGE;
2321      if (AB_address == 1)
2322         /* EOF */
2323         return IMGTOOLERR_UNEXPECTED;
2324      AB_address -= 2;
2325   }
2326
2327   *block_address = fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB
2328                  + block_num % fileref->l2_img->blocksperAB;
2329
2330   return IMGTOOLERR_SUCCESS;
2331}
2332
2333/*
2334   mfs_file_allocABs
2335
2336   Allocate a chunk of ABs
2337
2338   fileref (I/O): open mac file reference
2339   lastAB (I): AB address on disk of last file AB (only if
2340      fileref->u.mfs.stBlk != 1)
2341   allocABs (I): number of ABs to allocate in addition to the current file
2342      allocation
2343   fblock (I): first file block to allocate (used for tag data)
2344
2345   Return imgtool error code
2346*/
2347static imgtoolerr_t mfs_file_allocABs(mac_fileref *fileref, UINT16 lastAB, UINT32 allocABs, UINT32 fblock)
2348{
2349   int numABs = fileref->l2_img->numABs;
2350   int free_ABs;
2351   int i, j;
2352   floppy_tag_record tag;
2353   int extentBaseAB, extentABlen;
2354   int firstBestExtentBaseAB = 0, firstBestExtentABlen;
2355   int secondBestExtentBaseAB = 0, secondBestExtentABlen;
2356   imgtoolerr_t err;
2357
2358   /* return if done */
2359   if (! allocABs)
2360      return IMGTOOLERR_SUCCESS;
2361
2362   /* compute free space */
2363   free_ABs = 0;
2364   for (i=0; i<numABs; i++)
2365   {
2366      if (mfs_get_ABlink(fileref->l2_img, i) == 0)
2367      {
2368         if (TAG_CHECKS)
2369         {
2370            /* optional check */
2371            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2372            {
2373               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2374               {
2375                  err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + i * fileref->l2_img->blocksperAB + j, &tag);
2376                  if (err)
2377                     return err;
2378
2379                  if (get_UINT32BE(tag.fileID) != 0)
2380                  {
2381                     /*return IMGTOOLERR_CORRUPTIMAGE;*/
2382                     goto corrupt_free_block;
2383                  }
2384               }
2385            }
2386         }
2387
2388         free_ABs++;
2389      }
2390corrupt_free_block:
2391      ;
2392   }
2393
2394   /* check we have enough free space */
2395   if (free_ABs < allocABs)
2396      return IMGTOOLERR_NOSPACE;
2397
2398   if (fileref->u.mfs.stBlk != 1)
2399   {   /* try to extend last file extent */
2400      /* append free ABs after last AB */
2401      for (i=lastAB+1; (mfs_get_ABlink(fileref->l2_img, i) == 0) && (allocABs > 0) && (i < numABs); i++)
2402      {
2403         if (TAG_CHECKS)
2404         {
2405            /* optional check */
2406            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2407            {
2408               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2409               {
2410                  err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + i * fileref->l2_img->blocksperAB + j, &tag);
2411                  if (err)
2412                     return err;
2413
2414                  if (get_UINT32BE(tag.fileID) != 0)
2415                  {
2416                     /*return IMGTOOLERR_CORRUPTIMAGE;*/
2417                     goto corrupt_free_block2;
2418                  }
2419               }
2420            }
2421         }
2422
2423         mfs_set_ABlink(fileref->l2_img, lastAB, i+2);
2424         lastAB = i;
2425         allocABs--;
2426         free_ABs--;
2427      }
2428corrupt_free_block2:
2429      /* return if done */
2430      if (! allocABs)
2431      {
2432         mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2433         fileref->l2_img->freeABs = free_ABs;
2434         return IMGTOOLERR_SUCCESS;   /* done */
2435      }
2436   }
2437
2438   while (allocABs)
2439   {
2440      /* find smallest data block at least nb_alloc_physrecs in length, and largest data block less than nb_alloc_physrecs in length */
2441      firstBestExtentABlen = INT_MAX;
2442      secondBestExtentABlen = 0;
2443      for (i=0; i<numABs; i++)
2444      {
2445         if (mfs_get_ABlink(fileref->l2_img, i) == 0)
2446         {   /* found one free block */
2447            /* compute its length */
2448            extentBaseAB = i;
2449            extentABlen = 0;
2450            while ((i<numABs) && (mfs_get_ABlink(fileref->l2_img, i) == 0))
2451            {
2452               if (TAG_CHECKS)
2453               {
2454                  /* optional check */
2455                  if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2456                  {
2457                     for (j=0; j<fileref->l2_img->blocksperAB; j++)
2458                     {
2459                        err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + i * fileref->l2_img->blocksperAB + j, &tag);
2460                        if (err)
2461                           return err;
2462
2463                        if (get_UINT32BE(tag.fileID) != 0)
2464                        {
2465                           /*return IMGTOOLERR_CORRUPTIMAGE;*/
2466                           goto corrupt_free_block3;
2467                        }
2468                     }
2469                  }
2470               }
2471
2472               extentABlen++;
2473               i++;
2474            }
2475corrupt_free_block3:
2476            /* compare to previous best and second-best blocks */
2477            if ((extentABlen < firstBestExtentABlen) && (extentABlen >= allocABs))
2478            {
2479               firstBestExtentBaseAB = extentBaseAB;
2480               firstBestExtentABlen = extentABlen;
2481               if (extentABlen == allocABs)
2482                  /* no need to search further */
2483                  break;
2484            }
2485            else if ((extentABlen > secondBestExtentABlen) && (extentABlen < allocABs))
2486            {
2487               secondBestExtentBaseAB = extentBaseAB;
2488               secondBestExtentABlen = extentABlen;
2489            }
2490         }
2491      }
2492
2493      if (firstBestExtentABlen != INT_MAX)
2494      {   /* found one contiguous block which can hold it all */
2495         extentABlen = allocABs;
2496         for (i=0; i<allocABs; i++)
2497         {
2498            if (fileref->u.mfs.stBlk != 1)
2499               mfs_set_ABlink(fileref->l2_img, lastAB, firstBestExtentBaseAB+i+2);
2500            else
2501               fileref->u.mfs.stBlk = firstBestExtentBaseAB+i+2;
2502            lastAB = firstBestExtentBaseAB+i;
2503            free_ABs--;
2504            /* set tag to allocated */
2505            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2506            {
2507               set_UINT32BE(&tag.fileID, fileref->fileID);
2508               tag.ftype = 1;
2509               if ((fileref->forkType) == rsrc_fork)
2510                  tag.ftype |= 2;
2511               tag.fattr = /*fattr*/ 0;      /* ***TODO*** */
2512               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2513               {
2514                  set_UINT16BE(&tag.fblock, fblock & 0xffff);
2515                  set_UINT32BE(&tag.wrCnt, mac_time_now());
2516                  err = image_write_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + lastAB * fileref->l2_img->blocksperAB + j, &tag);
2517                  if (err)
2518                  {
2519                     mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2520                     fileref->l2_img->freeABs = free_ABs;
2521                     return err;
2522                  }
2523                  fblock++;
2524               }
2525            }
2526         }
2527         allocABs = 0;
2528         mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2529         fileref->l2_img->freeABs = free_ABs;
2530         /*return IMGTOOLERR_SUCCESS;*/   /* done */
2531      }
2532      else if (secondBestExtentABlen != 0)
2533      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
2534         for (i=0; i<secondBestExtentABlen; i++)
2535         {
2536            if (fileref->u.mfs.stBlk != 1)
2537               mfs_set_ABlink(fileref->l2_img, lastAB, secondBestExtentBaseAB+i+2);
2538            else
2539               fileref->u.mfs.stBlk = secondBestExtentBaseAB+i+2;
2540            lastAB = secondBestExtentBaseAB+i;
2541            free_ABs--;
2542            /* set tag to allocated */
2543            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2544            {
2545               set_UINT32BE(&tag.fileID, fileref->fileID);
2546               tag.ftype = 1;
2547               if ((fileref->forkType) == rsrc_fork)
2548                  tag.ftype |= 2;
2549               tag.fattr = /*fattr*/ 0;      /* ***TODO*** */
2550               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2551               {
2552                  set_UINT16BE(&tag.fblock, fblock & 0xffff);
2553                  set_UINT32BE(&tag.wrCnt, mac_time_now());
2554                  err = image_write_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + lastAB * fileref->l2_img->blocksperAB + j, &tag);
2555                  if (err)
2556                  {
2557                     mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2558                     fileref->l2_img->freeABs = free_ABs;
2559                     return err;
2560                  }
2561                  fblock++;
2562               }
2563            }
2564         }
2565         allocABs -= secondBestExtentABlen;
2566      }
2567      else
2568      {
2569         mfs_set_ABlink(fileref->l2_img, lastAB, 1);
2570         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
2571      }
2572   }
2573
2574   return IMGTOOLERR_SUCCESS;
2575}
2576
2577/*
2578   mfs_file_setABeof
2579
2580   Set physical file EOF in ABs
2581
2582   fileref (I/O): open mac file reference
2583   newABeof (I): desired number of allocated ABs for this file
2584
2585   Return imgtool error code
2586*/
2587static imgtoolerr_t mfs_file_setABeof(mac_fileref *fileref, UINT32 newABeof)
2588{
2589   UINT16 AB_address = 0;
2590   UINT16 AB_link;
2591   int i, j;
2592   floppy_tag_record tag;
2593   int MDB_dirty = 0;
2594   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
2595
2596
2597   assert(fileref->l2_img->format == L2I_MFS);
2598
2599   /* run through link chain until we reach the old or the new EOF */
2600   AB_link = fileref->u.mfs.stBlk;
2601   if ((AB_link == 0) || (AB_link >= fileref->l2_img->numABs+2))
2602      /* 0 -> ??? */
2603      return IMGTOOLERR_CORRUPTIMAGE;
2604   for (i=0; (i<newABeof) && (AB_link!=1); i++)
2605   {
2606      AB_address = AB_link - 2;
2607      AB_link = mfs_get_ABlink(fileref->l2_img, AB_address);
2608      if ((AB_link == 0) || (AB_link >= fileref->l2_img->numABs+2))
2609         /* 0 -> empty block: there is no way an empty block could make it
2610         into the link chain!!! */
2611         return IMGTOOLERR_CORRUPTIMAGE;
2612
2613      if (TAG_CHECKS)
2614      {
2615         /* optional check */
2616         if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2617         {
2618            for (j=0; j<fileref->l2_img->blocksperAB; j++)
2619            {
2620               err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB + j, &tag);
2621               if (err)
2622                  return err;
2623
2624               if ((get_UINT32BE(tag.fileID) != fileref->fileID)
2625                  || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
2626                  || (get_UINT16BE(tag.fblock) != ((i * fileref->l2_img->blocksperAB + j) & 0xffff)))
2627               {
2628                  return IMGTOOLERR_CORRUPTIMAGE;
2629               }
2630            }
2631         }
2632      }
2633   }
2634
2635   if (i == newABeof)
2636   {   /* new EOF is shorter than old one */
2637      /* mark new eof */
2638      if (i==0)
2639         fileref->u.mfs.stBlk = 1;
2640      else
2641      {
2642         mfs_set_ABlink(fileref->l2_img, AB_address, 1);
2643         MDB_dirty = 1;
2644      }
2645
2646      /* free all remaining blocks */
2647      while (AB_link != 1)
2648      {
2649         AB_address = AB_link - 2;
2650         AB_link = mfs_get_ABlink(fileref->l2_img, AB_address);
2651         if ((AB_link == 0) || (AB_link >= fileref->l2_img->numABs+2))
2652         {   /* 0 -> empty block: there is no way an empty block could make
2653            it into the link chain!!! */
2654            if (MDB_dirty)
2655            {   /* update MDB (freeABs field) and ABLink array */
2656               err = mfs_update_mdb(fileref->l2_img);
2657               if (err)
2658                  return err;
2659            }
2660            return IMGTOOLERR_CORRUPTIMAGE;
2661         }
2662
2663         if (TAG_CHECKS)
2664         {
2665            /* optional check */
2666            if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2667            {
2668               for (j=0; j<fileref->l2_img->blocksperAB; j++)
2669               {
2670                  err = image_read_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB + j, &tag);
2671                  if (err)
2672                     return err;
2673
2674                  if ((get_UINT32BE(tag.fileID) != fileref->fileID)
2675                     || (((tag.ftype & 2) != 0) != (fileref->forkType == rsrc_fork))
2676                     || (get_UINT16BE(tag.fblock) != ((i * fileref->l2_img->blocksperAB + j) & 0xffff)))
2677                  {
2678                     return IMGTOOLERR_CORRUPTIMAGE;
2679                  }
2680               }
2681            }
2682         }
2683
2684         mfs_set_ABlink(fileref->l2_img, AB_address, 0);
2685         fileref->l2_img->freeABs++;
2686         MDB_dirty = 1;
2687         /* set tag to free */
2688         if (image_get_tag_len(&fileref->l2_img->l1_img) == 12)
2689         {
2690            memset(&tag, 0, sizeof(tag));
2691            for (j=0; j<fileref->l2_img->blocksperAB; j++)
2692            {
2693               err = image_write_tag(&fileref->l2_img->l1_img, fileref->l2_img->u.mfs.ABStart + AB_address * fileref->l2_img->blocksperAB + j, &tag);
2694               if (err)
2695                  return err;
2696            }
2697         }
2698         i++;
2699      }
2700   }
2701   else
2702   {   /* new EOF is larger than old one */
2703      err = mfs_file_allocABs(fileref, AB_address, newABeof - i, i * fileref->l2_img->blocksperAB);
2704      if (err)
2705         return err;
2706      MDB_dirty = 1;
2707   }
2708
2709   if (MDB_dirty)
2710   {   /* update MDB (freeABs field) and ABLink array */
2711      err = mfs_update_mdb(fileref->l2_img);
2712      if (err)
2713         return err;
2714   }
2715
2716   fileref->pLen = newABeof * (fileref->l2_img->blocksperAB * 512);
2717
2718   return IMGTOOLERR_SUCCESS;
2719}
2720
2721#ifdef UNUSED_FUNCTION
2722/*
2723   mfs_hashString
2724
2725   Hash a string: under MFS, this provides the resource ID of the comment
2726   resource associated with the file whose name is provided (FCMT resource
2727   type).
2728
2729   Ripped from Apple technote TB06 (converted from 68k ASM to C)
2730
2731   string (I): string to hash
2732
2733   Returns hash value
2734*/
2735static int mfs_hashString(const mac_str255 string)
2736{
2737   int reply;
2738   int len;
2739   int i;
2740
2741   len = string[0];
2742
2743   reply = 0;
2744   for (i=0; i<len; i++)
2745   {
2746      reply ^= string[i+1];
2747      if (reply & 1)
2748         reply = ((reply >> 1) & 0x7fff) | ~0x7fff;
2749      else
2750         reply = ((reply >> 1) & 0x7fff);
2751      if (! (reply & 0x8000))
2752         reply = - reply;
2753   }
2754
2755   return reply;
2756}
2757#endif
2758
2759#if 0
2760#pragma mark -
2761#pragma mark HFS IMPLEMENTATION
2762#endif
2763
2764/*
2765   HFS extents B-tree key
2766*/
2767typedef struct hfs_extentKey
2768{
2769   UINT8    keyLength;      /* length of key, excluding this field */
2770   UINT8    forkType;      /* 0 = data fork, FF = resource fork */
2771   UINT32BE fileID;      /* file ID */
2772   UINT16BE startBlock;   /* first file allocation block number in this extent */
2773} hfs_extentKey;
2774enum
2775{
2776   keyLength_hfs_extentKey = sizeof(hfs_extentKey) - sizeof(UINT8)
2777};
2778
2779/*
2780   HFS catalog B-tree key
2781*/
2782typedef struct hfs_catKey
2783{
2784   UINT8    keyLen;      /* key length */
2785   UINT8    resrv1;      /* reserved */
2786   UINT32BE parID;         /* parent directory ID */
2787   mac_str31 cName;      /* catalog node name */
2788                     /* note that in index nodes, it is a mac_str31, but
2789                        in leaf keys it's a variable-length string */
2790} hfs_catKey;
2791
2792/*
2793   HFS catalog data record for a folder - 70 bytes
2794*/
2795typedef struct hfs_catFolderData
2796{
2797   UINT16BE recordType;      /* record type */
2798   UINT16BE flags;            /* folder flags */
2799   UINT16BE valence;         /* folder valence */
2800   UINT32BE folderID;         /* folder ID */
2801   UINT32BE createDate;      /* date and time of creation */
2802   UINT32BE modifyDate;      /* date and time of last modification */
2803   UINT32BE backupDate;      /* date and time of last backup */
2804   mac_DInfo userInfo;         /* Finder information */
2805   mac_DXInfo finderInfo;      /* additional Finder information */
2806   UINT32BE reserved[4];      /* reserved - set to zero */
2807} hfs_catFolderData;
2808
2809/*
2810   HFS catalog data record for a file - 102 bytes
2811*/
2812typedef struct hfs_catFileData
2813{
2814   UINT16BE recordType;      /* record type */
2815   UINT8    flags;            /* file flags */
2816   UINT8    fileType;         /* file type (reserved, always 0?) */
2817   mac_FInfo userInfo;         /* Finder information */
2818   UINT32BE fileID;         /* file ID */
2819   UINT16BE dataStartBlock;   /* not used - set to zero */
2820   UINT32BE dataLogicalSize;   /* logical EOF of data fork */
2821   UINT32BE dataPhysicalSize;   /* physical EOF of data fork */
2822   UINT16BE rsrcStartBlock;   /* not used - set to zero */
2823   UINT32BE rsrcLogicalSize;   /* logical EOF of resource fork */
2824   UINT32BE rsrcPhysicalSize;   /* physical EOF of resource fork */
2825   UINT32BE createDate;      /* date and time of creation */
2826   UINT32BE modifyDate;      /* date and time of last modification */
2827   UINT32BE backupDate;      /* date and time of last backup */
2828   mac_FXInfo finderInfo;      /* additional Finder information */
2829   UINT16BE clumpSize;         /* file clump size (not used) */
2830   hfs_extent_3 dataExtents;   /* first data fork extent record */
2831   hfs_extent_3 rsrcExtents;   /* first resource fork extent record */
2832   UINT32BE reserved;         /* reserved - set to zero */
2833} hfs_catFileData;
2834
2835/*
2836   HFS catalog data record for a thread - 46 bytes
2837
2838   The key for a thread record features the CNID of the item and an empty
2839   name, instead of the CNID of the parent and the item name.
2840*/
2841typedef struct hfs_catThreadData
2842{
2843   UINT16BE recordType;      /* record type */
2844   UINT32BE reserved[2];      /* reserved - set to zero */
2845   UINT32BE parID;            /* parent ID for this catalog node */
2846   mac_str31 nodeName;         /* name of this catalog node */
2847} hfs_catThreadData;
2848
2849/*
2850   union for all types at once
2851*/
2852typedef union hfs_catData
2853{
2854   UINT16BE dataType;
2855   hfs_catFolderData folder;
2856   hfs_catFileData file;
2857   hfs_catThreadData thread;
2858} hfs_catData;
2859
2860/*
2861   HFS catalog record types
2862*/
2863enum
2864{
2865   hcrt_Folder         = 0x0100,   /* Folder record */
2866   hcrt_File         = 0x0200,   /* File record */
2867   hcrt_FolderThread   = 0x0300,   /* Folder thread record */
2868   hcrt_FileThread      = 0x0400   /* File thread record */
2869};
2870
2871/*
2872   Catalog file record flags
2873
2874   This is similar to the MFS catalog flag field, but the "thread exists" flag
2875   (0x02) is specific to HFS/HFS+, whereas the "Record in use" flag (0x80) is
2876   only used by MFS.
2877*/
2878enum
2879{
2880   cfrf_fileLocked      = 0x01,      /* file is locked and cannot be written to */
2881   cfrf_threadExists   = 0x02      /* a file thread record exists for this file */
2882};
2883
2884/*
2885   BT functions used by HFS functions
2886*/
2887typedef struct BT_leaf_rec_enumerator
2888{
2889   mac_BTref *BTref;
2890   UINT32 cur_node;
2891   int cur_rec;
2892} BT_leaf_rec_enumerator;
2893
2894static imgtoolerr_t BT_open(mac_BTref *BTref, int (*key_compare_func)(const void *key1, const void *key2), int is_extent);
2895static void BT_close(mac_BTref *BTref);
2896static imgtoolerr_t BT_search_leaf_rec(mac_BTref *BTref, const void *search_key,
2897                        UINT32 *node_ID, int *record_ID,
2898                        void **record_ptr, int *record_len,
2899                        int search_exact_match, int *match_found);
2900static imgtoolerr_t BT_get_keyed_record_data(mac_BTref *BTref, void *rec_ptr, int rec_len, void **data_ptr, int *data_len);
2901static imgtoolerr_t BT_leaf_rec_enumerator_open(mac_BTref *BTref, BT_leaf_rec_enumerator *enumerator);
2902static imgtoolerr_t BT_leaf_rec_enumerator_read(BT_leaf_rec_enumerator *enumerator, void **record_ptr, int *rec_len);
2903
2904typedef struct hfs_cat_enumerator
2905{
2906   mac_l2_imgref *l2_img;
2907   BT_leaf_rec_enumerator BT_enumerator;
2908   UINT32 parID;
2909} hfs_cat_enumerator;
2910
2911/*
2912   hfs_open_extents_file
2913
2914   Open the file extents B-tree file
2915
2916   l2_img (I/O): level-2 image reference
2917   mdb (I): copy of the MDB block
2918   fileref (O): mac open file reference
2919
2920   Return imgtool error code
2921*/
2922static imgtoolerr_t hfs_open_extents_file(mac_l2_imgref *l2_img, const hfs_mdb *mdb, mac_fileref *fileref)
2923{
2924   assert(l2_img->format == L2I_HFS);
2925
2926   fileref->l2_img = l2_img;
2927
2928   fileref->fileID = 3;
2929   fileref->forkType = 0x00;
2930
2931   fileref->eof = fileref->pLen = get_UINT32BE(mdb->xtFlSize);
2932   memcpy(fileref->u.hfs.extents, mdb->xtExtRec, sizeof(hfs_extent_3));
2933
2934   fileref->crPs = 0;
2935
2936   fileref->reload_buf = TRUE;
2937
2938   return IMGTOOLERR_SUCCESS;
2939}
2940
2941/*
2942   hfs_open_cat_file
2943
2944   Open the disk catalog B-tree file
2945
2946   l2_img (I/O): level-2 image reference
2947   mdb (I): copy of the MDB block
2948   fileref (O): mac open file reference
2949
2950   Return imgtool error code
2951*/
2952static imgtoolerr_t hfs_open_cat_file(mac_l2_imgref *l2_img, const hfs_mdb *mdb, mac_fileref *fileref)
2953{
2954   assert(l2_img->format == L2I_HFS);
2955
2956   fileref->l2_img = l2_img;
2957
2958   fileref->fileID = 4;
2959   fileref->forkType = 0x00;
2960
2961   fileref->eof = fileref->pLen = get_UINT32BE(mdb->ctFlSize);
2962   memcpy(fileref->u.hfs.extents, mdb->ctExtRec, sizeof(hfs_extent_3));
2963
2964   fileref->crPs = 0;
2965
2966   fileref->reload_buf = TRUE;
2967
2968   return IMGTOOLERR_SUCCESS;
2969}
2970
2971/*
2972   hfs_extentKey_compare
2973
2974   key compare function for file extents B-tree
2975
2976   p1 (I): pointer to first key
2977   p2 (I): pointer to second key
2978
2979   Return a zero the two keys are equal, a negative value if the key pointed
2980   to by p1 is less than the key pointed to by p2, and a positive value if the
2981   key pointed to by p1 is greater than the key pointed to by p2.
2982*/
2983static int hfs_extentKey_compare(const void *p1, const void *p2)
2984{
2985   const hfs_extentKey *key1 = p1;
2986   const hfs_extentKey *key2 = p2;
2987
2988   /* let's keep it simple for now */
2989   return memcmp(key1, key2, sizeof(hfs_extentKey));
2990}
2991
2992/*
2993   hfs_catKey_compare
2994
2995   key compare function for disk catalog B-tree
2996
2997   p1 (I): pointer to first key
2998   p2 (I): pointer to second key
2999
3000   Return a zero the two keys are equal, a negative value if the key pointed
3001   to by p1 is less than the key pointed to by p2, and a positive value if the
3002   key pointed to by p1 is greater than the key pointed to by p2.
3003*/
3004static int hfs_catKey_compare(const void *p1, const void *p2)
3005{
3006   const hfs_catKey *key1 = p1;
3007   const hfs_catKey *key2 = p2;
3008
3009   if (get_UINT32BE(key1->parID) != get_UINT32BE(key2->parID))
3010      return (get_UINT32BE(key1->parID) < get_UINT32BE(key2->parID)) ? -1 : +1;
3011
3012   return mac_stricmp(key1->cName, key2->cName);
3013}
3014
3015/*
3016   hfs_image_open
3017
3018   Open a HFS image.  Image must already be open on level 1.
3019
3020   l2_img (I/O): level-2 image reference to open (l1_img and format fields
3021      must be initialized)
3022   img_open_buf (I): buffer with the MDB block
3023
3024   Return imgtool error code
3025*/
3026static imgtoolerr_t hfs_image_open(imgtool_image *image, imgtool_stream *stream)
3027{
3028   imgtoolerr_t err;
3029   mac_l2_imgref *l2_img;
3030   img_open_buf buf_local;
3031   img_open_buf *buf;
3032
3033   l2_img = get_imgref(image);
3034   l2_img->l1_img.image = image;
3035   l2_img->l1_img.heads = 2;
3036   l2_img->format = L2I_HFS;
3037
3038   /* read MDB */
3039   err = image_read_block(&l2_img->l1_img, 2, &buf_local.raw);
3040   if (err)
3041      return err;
3042   buf = &buf_local;
3043
3044   /* check signature word */
3045   if ((buf->hfs_mdb.sigWord[0] != 0x42) || (buf->hfs_mdb.sigWord[1] != 0x44)
3046         || (buf->hfs_mdb.VN[0] > 27))
3047      return IMGTOOLERR_CORRUPTIMAGE;
3048
3049   l2_img->u.hfs.VBM_start = get_UINT16BE(buf->hfs_mdb.VBMSt);
3050
3051   l2_img->numABs = get_UINT16BE(buf->hfs_mdb.nmAlBlks);
3052   if (get_UINT32BE(buf->hfs_mdb.alBlkSiz) % 512)
3053      return IMGTOOLERR_CORRUPTIMAGE;
3054   l2_img->blocksperAB = get_UINT32BE(buf->hfs_mdb.alBlkSiz) / 512;
3055   l2_img->u.hfs.ABStart = get_UINT16BE(buf->hfs_mdb.alBlSt);
3056
3057   l2_img->nxtCNID = get_UINT32BE(buf->hfs_mdb.nxtCNID);
3058
3059   l2_img->freeABs = get_UINT16BE(buf->hfs_mdb.freeABs);
3060
3061   mac_strcpy(l2_img->u.hfs.volname, buf->hfs_mdb.VN);
3062
3063   /* open extents and catalog BT */
3064   err = hfs_open_extents_file(l2_img, &buf->hfs_mdb, &l2_img->u.hfs.extents_BT.fileref);
3065   if (err)
3066      return err;
3067   err = BT_open(&l2_img->u.hfs.extents_BT, hfs_extentKey_compare, TRUE);
3068   if (err)
3069      return err;
3070   if ((l2_img->u.hfs.extents_BT.attributes & btha_bigKeysMask)
3071         /*|| (l2_img->u.hfs.extents_BT.attributes & kBTVariableIndexKeysMask)*/
3072         || (l2_img->u.hfs.extents_BT.maxKeyLength != 7))
3073   {   /* This is not supported by the HFS format */
3074      /* Variable Index keys are not supported either, but hopefully it will
3075      not break this imgtool module if it set (though it would probably break
3076      a real macintosh) */
3077      BT_close(&l2_img->u.hfs.extents_BT);
3078      return IMGTOOLERR_CORRUPTIMAGE;
3079   }
3080   err = hfs_open_cat_file(l2_img, &buf->hfs_mdb, &l2_img->u.hfs.cat_BT.fileref);
3081   if (err)
3082   {
3083      BT_close(&l2_img->u.hfs.extents_BT);
3084      return err;
3085   }
3086   err = BT_open(&l2_img->u.hfs.cat_BT, hfs_catKey_compare, FALSE);
3087   if (err)
3088   {
3089      return err;
3090   }
3091   if ((l2_img->u.hfs.cat_BT.attributes & btha_bigKeysMask)
3092         /*|| (l2_img->u.hfs.cat_BT.attributes & kBTVariableIndexKeysMask)*/
3093         || (l2_img->u.hfs.cat_BT.maxKeyLength != 37))
3094   {   /* This is not supported by the HFS format */
3095      /* Variable Index keys are not supported either, but hopefully it will
3096      not break this imgtool module if it set (though it would probably break
3097      a real macintosh) */
3098      BT_close(&l2_img->u.hfs.extents_BT);
3099      BT_close(&l2_img->u.hfs.cat_BT);
3100      return IMGTOOLERR_CORRUPTIMAGE;
3101   }
3102
3103   /* extract volume bitmap */
3104   {
3105      int byte_len = (l2_img->numABs + 7) / 8;
3106      int cur_byte = 0;
3107      int cur_block = l2_img->u.hfs.VBM_start;
3108
3109      while (cur_byte < byte_len)
3110      {
3111         /* read next block */
3112         err = image_read_block(&l2_img->l1_img, cur_block, buf->raw);
3113         if (err)
3114            return err;
3115         cur_block++;
3116
3117         /* append this block to VBM */
3118         memcpy(l2_img->u.hfs.VBM+cur_byte, buf->raw, 512);
3119         cur_byte += 512;
3120      }
3121   }
3122
3123   return IMGTOOLERR_SUCCESS;
3124}
3125
3126#ifdef UNUSED_FUNCTION
3127/*
3128   hfs_image_close
3129
3130   Close a HFS image.
3131
3132   l2_img (I/O): level-2 image reference
3133*/
3134static void hfs_image_close(mac_l2_imgref *l2_img)
3135{
3136   assert(l2_img->format == L2I_HFS);
3137
3138   BT_close(&l2_img->u.hfs.extents_BT);
3139   BT_close(&l2_img->u.hfs.cat_BT);
3140}
3141#endif
3142
3143/*
3144   hfs_get_cat_record_data
3145
3146   extract data from a catalog B-tree leaf record
3147
3148   l2_img (I/O): level-2 image reference
3149   rec_raw (I): pointer to record key and data, as returned by
3150      BT_node_get_keyed_record
3151   rec_len (I): total length of record, as returned by
3152      BT_node_get_keyed_record
3153   rec_key (O): set to point to record key
3154   rec_data (O): set to point to record data
3155
3156   Return imgtool error code
3157*/
3158static imgtoolerr_t hfs_get_cat_record_data(mac_l2_imgref *l2_img, void *rec_raw, int rec_len, hfs_catKey **rec_key, hfs_catData **rec_data)
3159{
3160   hfs_catKey *lrec_key;
3161   void *rec_data_raw;
3162   hfs_catData *lrec_data;
3163   int rec_data_len;
3164   int min_data_size;
3165   imgtoolerr_t err;
3166
3167
3168   assert(l2_img->format == L2I_HFS);
3169
3170   lrec_key = rec_raw;
3171   /* check that key is long enough to hold it all */
3172   if ((lrec_key->keyLen+1) < (offsetof(hfs_catKey, cName) + lrec_key->cName[0] + 1))
3173      return IMGTOOLERR_CORRUPTIMAGE;
3174
3175   /* get pointer to record data */
3176   err = BT_get_keyed_record_data(&l2_img->u.hfs.cat_BT, rec_raw, rec_len, &rec_data_raw, &rec_data_len);
3177   if (err)
3178      return err;
3179   lrec_data = rec_data_raw;
3180
3181   /* extract record type */
3182   if (rec_data_len < 2)
3183      return IMGTOOLERR_CORRUPTIMAGE;
3184
3185   /* check that the record is large enough for its type */
3186   switch (get_UINT16BE(lrec_data->dataType))
3187   {
3188   case hcrt_Folder:
3189      min_data_size = sizeof(hfs_catFolderData);
3190      break;
3191
3192   case hcrt_File:
3193      min_data_size = sizeof(hfs_catFileData);
3194      break;
3195
3196   case hcrt_FolderThread:
3197   case hcrt_FileThread:
3198      min_data_size = sizeof(hfs_catThreadData);
3199      break;
3200
3201   default:
3202      /* records of unknown type can be safely ignored */
3203      min_data_size = 0;
3204      break;
3205   }
3206
3207   if (rec_data_len < min_data_size)
3208      return IMGTOOLERR_CORRUPTIMAGE;
3209
3210   if (rec_key)
3211      *rec_key = lrec_key;
3212   if (rec_data)
3213      *rec_data = lrec_data;
3214
3215   return IMGTOOLERR_SUCCESS;
3216}
3217
3218/*
3219   hfs_cat_open
3220
3221   Open an enumerator on the disk catalog
3222
3223   l2_img (I/O): level-2 image reference
3224   enumerator (O): open catalog enumerator reference
3225
3226   Return imgtool error code
3227*/
3228static imgtoolerr_t hfs_cat_open(mac_l2_imgref *l2_img, const char *path, hfs_cat_enumerator *enumerator)
3229{
3230   imgtoolerr_t err;
3231   UINT32 parID;
3232   mac_str255 filename;
3233   mac_dirent cat_info;
3234
3235   assert(l2_img->format == L2I_HFS);
3236
3237   /* resolve path and fetch file info from directory/catalog */
3238   err = mac_lookup_path(l2_img, path, &parID, filename, &cat_info, FALSE);
3239   if (err)
3240      return err;
3241   if (cat_info.dataRecType != hcrt_Folder)
3242      return IMGTOOLERR_FILENOTFOUND;
3243
3244   enumerator->l2_img = l2_img;
3245   enumerator->parID = parID;
3246
3247   return BT_leaf_rec_enumerator_open(&l2_img->u.hfs.cat_BT, &enumerator->BT_enumerator);
3248}
3249
3250/*
3251   hfs_cat_read
3252
3253   Enumerate the disk catalog
3254
3255   enumerator (I/O): open catalog enumerator reference
3256   rec_key (O): set to point to record key
3257   rec_data (O): set to point to record data
3258
3259   Return imgtool error code
3260*/
3261static imgtoolerr_t hfs_cat_read(hfs_cat_enumerator *enumerator, hfs_catKey **rec_key, hfs_catData **rec_data)
3262{
3263   void *rec;
3264   int rec_len;
3265   imgtoolerr_t err;
3266
3267
3268   *rec_key = NULL;
3269   *rec_data = NULL;
3270
3271   /* read next record */
3272   err = BT_leaf_rec_enumerator_read(&enumerator->BT_enumerator, &rec, &rec_len);
3273   if (err)
3274      return err;
3275
3276   /* check EOList condition */
3277   if (rec == NULL)
3278      return IMGTOOLERR_SUCCESS;
3279
3280   /* extract record data */
3281   err = hfs_get_cat_record_data(enumerator->l2_img, rec, rec_len, rec_key, rec_data);
3282   if (err)
3283      return err;
3284
3285   return IMGTOOLERR_SUCCESS;
3286}
3287
3288/*
3289   hfs_cat_search
3290
3291   Search the catalog for a given file
3292
3293   l2_img (I/O): level-2 image reference
3294   parID (I): CNID of file parent directory
3295   cName (I): file name
3296   rec_key (O): set to point to record key
3297   rec_data (O): set to point to record data
3298
3299   Return imgtool error code
3300*/
3301static imgtoolerr_t hfs_cat_search(mac_l2_imgref *l2_img, UINT32 parID, const mac_str31 cName, hfs_catKey **rec_key, hfs_catData **rec_data)
3302{
3303   hfs_catKey search_key;
3304   void *rec;
3305   int rec_len;
3306   imgtoolerr_t err;
3307
3308   assert(l2_img->format == L2I_HFS);
3309
3310   if (cName[0] > 31)
3311      return IMGTOOLERR_UNEXPECTED;
3312
3313   /* generate search key */
3314   search_key.keyLen = search_key.resrv1 = 0;   /* these fields do not matter
3315                                    to the compare function, so we
3316                                    don't fill them */
3317   set_UINT32BE(&search_key.parID, parID);
3318   mac_strcpy(search_key.cName, cName);
3319
3320   /* search key */
3321   err = BT_search_leaf_rec(&l2_img->u.hfs.cat_BT, &search_key, NULL, NULL, &rec, &rec_len, TRUE, NULL);
3322   if (err)
3323      return err;
3324
3325   /* extract record data */
3326   err = hfs_get_cat_record_data(l2_img, rec, rec_len, rec_key, rec_data);
3327   if (err)
3328      return err;
3329
3330   return IMGTOOLERR_SUCCESS;
3331}
3332
3333/*
3334   hfs_lookup_path
3335
3336   Resolve a file path
3337
3338   l2_img (I/O): level-2 image reference
3339   fpath (I): file path (C string)
3340   parID (O): set to the CNID of the file parent directory
3341   filename (O): set to the actual name of the file, with capitalization matching
3342      the one on the volume rather than the one in the fpath parameter (Mac
3343      string)
3344   cat_info (O): catalog info for this file extracted from the catalog file
3345      (may be NULL)
3346
3347   Return imgtool error code
3348*/
3349static imgtoolerr_t hfs_lookup_path(mac_l2_imgref *l2_img, const char *fpath, UINT32 *parID, mac_str255 filename, mac_dirent *cat_info)
3350{
3351   const char *element_start;
3352   int element_len;
3353   mac_str255 mac_element_name;
3354   int level;
3355   imgtoolerr_t err;
3356   hfs_catKey *catrec_key = NULL;
3357   hfs_catData *catrec_data = NULL;
3358   UINT16 dataRecType = hcrt_Folder;
3359
3360   /* iterate each path element */
3361   element_start = fpath;
3362   level = 0;
3363   *parID = 2;   /* root parID is 2 */
3364
3365   while(*element_start)
3366   {
3367      /* find next path element */
3368      element_len = strlen(element_start);
3369      /* decode path element name */
3370      c_to_mac_strncpy(mac_element_name, element_start, element_len);
3371
3372      err = hfs_cat_search(l2_img, *parID, mac_element_name, &catrec_key, &catrec_data);
3373      if (err)
3374         return err;
3375
3376      dataRecType = get_UINT16BE(catrec_data->dataType);
3377
3378      /* regular folder/file name */
3379      if (dataRecType == hcrt_Folder)
3380         *parID = get_UINT32BE(catrec_data->folder.folderID);
3381      else if (element_start[element_len + 1])
3382         return IMGTOOLERR_BADFILENAME;
3383
3384      /* iterate */
3385      element_start += element_len + 1;
3386   }
3387
3388   if (catrec_key && (dataRecType == hcrt_File))
3389   {
3390      /* save ref */
3391      *parID = get_UINT32BE(catrec_key->parID);
3392      mac_strcpy(filename, catrec_key->cName);
3393   }
3394
3395   if (cat_info)
3396   {
3397      if (catrec_data && (dataRecType == hcrt_File))
3398      {
3399         cat_info->flFinderInfo = catrec_data->file.userInfo;
3400         cat_info->flXFinderInfo = catrec_data->file.finderInfo;
3401         cat_info->flags = catrec_data->file.flags;
3402         cat_info->fileID = get_UINT32BE(catrec_data->file.fileID);
3403         cat_info->dataLogicalSize = get_UINT32BE(catrec_data->file.dataLogicalSize);
3404         cat_info->dataPhysicalSize = get_UINT32BE(catrec_data->file.dataPhysicalSize);
3405         cat_info->rsrcLogicalSize = get_UINT32BE(catrec_data->file.rsrcLogicalSize);
3406         cat_info->rsrcPhysicalSize = get_UINT32BE(catrec_data->file.rsrcPhysicalSize);
3407         cat_info->createDate = get_UINT32BE(catrec_data->file.createDate);
3408         cat_info->modifyDate = get_UINT32BE(catrec_data->file.modifyDate);
3409      }
3410      else
3411      {
3412         memset(cat_info, 0, sizeof(*cat_info));
3413      }
3414      cat_info->dataRecType = dataRecType;
3415   }
3416
3417   return IMGTOOLERR_SUCCESS;
3418}
3419
3420/*
3421   hfs_file_open_internal
3422
3423   Open a file fork, given its catalog entry.  This function should not be
3424   called directly: call hfs_file_open instead.
3425
3426   l2_img (I/O): level-2 image reference
3427   file_rec (I): catalog entry for the file to open
3428   mac_forkID (I): tells which fork should be opened
3429   fileref (O): mac file reference to open
3430
3431   Return imgtool error code
3432*/
3433static imgtoolerr_t hfs_file_open_internal(mac_l2_imgref *l2_img, const hfs_catFileData *file_rec, mac_forkID fork, mac_fileref *fileref)
3434{
3435   assert(l2_img->format == L2I_HFS);
3436
3437   fileref->l2_img = l2_img;
3438
3439   fileref->fileID = get_UINT32BE(file_rec->fileID);
3440   fileref->forkType = fork;
3441
3442   switch (fork)
3443   {
3444   case data_fork:
3445      fileref->eof = get_UINT32BE(file_rec->dataLogicalSize);
3446      fileref->pLen = get_UINT32BE(file_rec->dataPhysicalSize);
3447      memcpy(fileref->u.hfs.extents, file_rec->dataExtents, sizeof(hfs_extent_3));
3448      break;
3449
3450   case rsrc_fork:
3451      fileref->eof = get_UINT32BE(file_rec->rsrcLogicalSize);
3452      fileref->pLen = get_UINT32BE(file_rec->rsrcPhysicalSize);
3453      memcpy(fileref->u.hfs.extents, file_rec->rsrcExtents, sizeof(hfs_extent_3));
3454      break;
3455   }
3456
3457   fileref->crPs = 0;
3458
3459   fileref->reload_buf = TRUE;
3460
3461   return IMGTOOLERR_SUCCESS;
3462}
3463
3464/*
3465   hfs_file_open
3466
3467   Open a file located on a HFS volume.  This function should not be called
3468   directly: call mac_file_open instead.
3469
3470   l2_img (I/O): level-2 image reference
3471   parID (I): CNID of file parent directory
3472   filename (I): name of the file (Mac string)
3473   mac_forkID (I): tells which fork should be opened
3474   fileref (O): mac file reference to open
3475
3476   Return imgtool error code
3477*/
3478static imgtoolerr_t hfs_file_open(mac_l2_imgref *l2_img, UINT32 parID, const mac_str255 filename, mac_forkID fork, mac_fileref *fileref)
3479{
3480   hfs_catKey *catrec_key;
3481   hfs_catData *catrec_data;
3482   UINT16 dataRecType;
3483   imgtoolerr_t err;
3484
3485   /* lookup file in catalog */
3486   err = hfs_cat_search(l2_img, parID, filename, &catrec_key, &catrec_data);
3487   if (err)
3488      return err;
3489
3490   dataRecType = get_UINT16BE(catrec_data->dataType);
3491
3492   /* file expected */
3493   if (dataRecType != hcrt_File)
3494      return IMGTOOLERR_BADFILENAME;
3495
3496   fileref->u.hfs.parID = get_UINT32BE(catrec_key->parID);
3497   mac_strcpy(fileref->u.hfs.filename, catrec_key->cName);
3498
3499   /* open it */
3500   return hfs_file_open_internal(l2_img, &catrec_data->file, fork, fileref);
3501}
3502
3503/*
3504   hfs_file_get_nth_block_address
3505
3506   Get the disk block address of a given block in an open file on a MFS image.
3507   Called by macintosh file code.
3508
3509   fileref (I/O): open mac file reference
3510   block_num (I): file block index
3511   block_address (O): disk block address for the file block
3512
3513   Return imgtool error code
3514*/
3515static imgtoolerr_t hfs_file_get_nth_block_address(mac_fileref *fileref, UINT32 block_num, UINT32 *block_address)
3516{
3517   UINT32 AB_num;
3518   UINT32 cur_AB;
3519   UINT32 i;
3520   void *cur_extents_raw;
3521   hfs_extent *cur_extents;
3522   int cur_extents_len;
3523   void *extents_BT_rec;
3524   int extents_BT_rec_len;
3525   imgtoolerr_t err;
3526   UINT16 AB_address;
3527
3528   assert(fileref->l2_img->format == L2I_HFS);
3529
3530   AB_num = block_num / fileref->l2_img->blocksperAB;
3531   cur_AB = 0;
3532   cur_extents = fileref->u.hfs.extents;
3533
3534   /* first look in catalog tree extents */
3535   for (i=0; i<3; i++)
3536   {
3537      if (AB_num < cur_AB+get_UINT16BE(cur_extents[i].numABlks))
3538         break;
3539      cur_AB += get_UINT16BE(cur_extents[i].numABlks);
3540   }
3541   if (i == 3)
3542   {
3543      /* extent not found: read extents record from extents BT */
3544      hfs_extentKey search_key;
3545      hfs_extentKey *found_key;
3546
3547      search_key.keyLength = keyLength_hfs_extentKey;
3548      search_key.forkType = fileref->forkType;
3549      set_UINT32BE(&search_key.fileID, fileref->fileID);
3550      set_UINT16BE(&search_key.startBlock, AB_num);
3551
3552      /* search for the record with the largest key lower than or equal to
3553      search_key.  The keys are constructed in such a way that, if a record
3554      includes AB_num, it is that one. */
3555      err = BT_search_leaf_rec(&fileref->l2_img->u.hfs.extents_BT, &search_key,
3556                              NULL, NULL, &extents_BT_rec, &extents_BT_rec_len,
3557                              FALSE, NULL);
3558      if (err)
3559         return err;
3560
3561      if (extents_BT_rec == NULL)
3562         return IMGTOOLERR_CORRUPTIMAGE;
3563
3564      found_key = extents_BT_rec;
3565      /* check that this record concerns the correct file */
3566      if ((found_key->forkType != fileref->forkType)
3567         || (get_UINT32BE(found_key->fileID) != fileref->fileID))
3568         return IMGTOOLERR_CORRUPTIMAGE;
3569
3570      /* extract start AB */
3571      cur_AB = get_UINT16BE(found_key->startBlock);
3572      /* get extents pointer */
3573      err = BT_get_keyed_record_data(&fileref->l2_img->u.hfs.extents_BT, extents_BT_rec, extents_BT_rec_len, &cur_extents_raw, &cur_extents_len);
3574      if (err)
3575         return err;
3576      if (cur_extents_len < 3*sizeof(hfs_extent))
3577         return IMGTOOLERR_CORRUPTIMAGE;
3578      cur_extents = cur_extents_raw;
3579
3580      /* pick correct extent in record */
3581      for (i=0; i<3; i++)
3582      {
3583         if (AB_num < cur_AB+get_UINT16BE(cur_extents[i].numABlks))
3584            break;
3585         cur_AB += get_UINT16BE(cur_extents[i].numABlks);
3586      }
3587      if (i == 3)
3588         /* extent not found */
3589         return IMGTOOLERR_CORRUPTIMAGE;
3590   }
3591
3592   AB_address = get_UINT16BE(cur_extents[i].stABN) + (AB_num-cur_AB);
3593
3594   if (AB_address >= fileref->l2_img->numABs)
3595      return IMGTOOLERR_CORRUPTIMAGE;
3596
3597   *block_address = fileref->l2_img->u.hfs.ABStart + AB_address * fileref->l2_img->blocksperAB
3598                  + block_num % fileref->l2_img->blocksperAB;
3599
3600   return IMGTOOLERR_SUCCESS;
3601}
3602
3603#if 0
3604#pragma mark -
3605#pragma mark B-TREE IMPLEMENTATION
3606#endif
3607
3608/*
3609   B-tree (Balanced search tree) files are used by the HFS and HFS+ file
3610   systems: the Extents and Catalog files are both B-Tree.
3611
3612   Note that these B-trees are B+-trees: data is only on the leaf level, and
3613   nodes located on the same level are also linked sequentially, which allows
3614   fast sequenctial access to the catalog file.
3615
3616   These files are normal files, except for the fact that they are not
3617   referenced from the catalog but the MDB.  They are allocated in fixed-size
3618   records of 512 bytes (HFS).  (HFS+ supports any power of two from 512
3619   through 32768, and uses a default of 1024 for Extents, and 4096 for both
3620   Catalog and Attributes.)
3621
3622   Nodes can contain any number of records.  The nodes can be of any of four
3623   types: header node (unique node with b-tree information, pointer to root
3624   node and start of the node allocation bitmap), map nodes (which are created
3625   when the node allocation bitmap outgrows the header node), index nodes
3626   (root and branch node that enable to efficiently search the leaf nodes for
3627   a specific key value), and leaf nodes (which hold the actual user data
3628   records with keys and data).  The first node is always a header node.
3629   Other nodes can be of any of the 3 other type, or they can be free.
3630*/
3631
3632/*
3633   BTNodeHeader
3634
3635   Header of a node record
3636*/
3637typedef struct BTNodeHeader
3638{
3639   UINT32BE fLink;         /* (index of) next node at this level */
3640   UINT32BE bLink;         /* (index of) previous node at this level */
3641   UINT8    kind;         /* kind of node (leaf, index, header, map) */
3642   UINT8    height;      /* zero for header, map; 1 for leaf, 2 through
3643                        treeDepth for index (child is one LESS than
3644                        parent, whatever IM says) */
3645   UINT16BE numRecords;   /* number of records in this node */
3646   UINT16BE reserved;      /* reserved; set to zero */
3647} BTNodeHeader;
3648
3649/*
3650   Constants for BTNodeHeader kind field
3651*/
3652enum
3653{
3654   btnk_leafNode   = 0xff,   /* leaf nodes hold the actual user data records
3655                        with keys and data */
3656   btnk_indexNode   = 0,   /* root and branch node that enable to efficiently
3657                        search the leaf nodes for a specific key value */
3658   btnk_headerNode   = 1,   /* unique node with b-tree information, pointer to
3659                        root node and start of the node allocation
3660                        bitmap */
3661   btnk_mapNode   = 2      /* map nodes are created when the node allocation
3662                        bitmap outgrows the header node */
3663};
3664
3665/*
3666   BTHeaderRecord: first record of a B-tree header node (second record is
3667   unused, and third is node allocation bitmap).
3668*/
3669typedef struct BTHeaderRecord
3670{
3671   UINT16BE treeDepth;      /* maximum height (usually leaf nodes) */
3672   UINT32BE rootNode;      /* node number of root node */
3673   UINT32BE leafRecords;   /* number of leaf records in all leaf nodes */
3674   UINT32BE firstLeafNode;   /* node number of first leaf node */
3675   UINT32BE lastLeafNode;   /* node number of last leaf node */
3676   UINT16BE nodeSize;      /* size of a node, in bytes */
3677   UINT16BE maxKeyLength;   /* maximum length of data (index + leaf) record keys;
3678                        length of all index record keys if
3679                        btha_variableIndexKeysMask attribute flag is not set */
3680   UINT32BE totalNodes;   /* total number of nodes in tree */
3681   UINT32BE freeNodes;      /* number of unused (free) nodes in tree */
3682
3683   UINT16BE reserved1;      /* unused */
3684   UINT32BE clumpSize;      /* used in some HFS implementations? (reserved in
3685                        early HFS implementations, and in HFS Plus) */
3686   UINT8    btreeType;      /* reserved - set to 0 */
3687   UINT8    reserved2;      /* reserved */
3688   UINT32BE attributes;   /* persistent attributes about the tree */
3689   UINT32BE reserved3[16];   /* reserved */
3690} BTHeaderRecord;
3691
3692static imgtoolerr_t BT_check(mac_BTref *BTref, int is_extent);
3693
3694/*
3695   BT_open
3696
3697   Open a file as a B-tree.  The file must be already open as a macintosh
3698   file.
3699
3700   BTref (I/O): B-tree file handle to open (BTref->fileref must have been
3701      open previously)
3702   key_compare_func (I): function that compares two keys
3703   is_extent (I): TRUE if we are opening the extent B-tree (we want to do
3704      extra checks in this case because the extent B-Tree may include extent
3705      records for the extent B-tree itself, and if an extent record for the
3706      extent B-tree is located in an extent that has not been defined by
3707      previous extent records, then we can never retreive this extent record)
3708
3709   Return imgtool error code
3710*/
3711static imgtoolerr_t BT_open(mac_BTref *BTref, int (*key_compare_func)(const void *key1, const void *key2), int is_extent)
3712{
3713   imgtoolerr_t err;
3714   BTNodeHeader node_header;
3715   BTHeaderRecord header_rec;
3716
3717   /* seek to node 0 */
3718   err = mac_file_seek(&BTref->fileref, 0);
3719   if (err)
3720      return err;
3721
3722   /* read node header */
3723   err = mac_file_read(&BTref->fileref, sizeof(node_header), &node_header);
3724   if (err)
3725      return err;
3726
3727   if ((node_header.kind != btnk_headerNode) || (get_UINT16BE(node_header.numRecords) < 3)
3728         || (node_header.height != 0))
3729      return IMGTOOLERR_CORRUPTIMAGE;   /* right??? */
3730
3731   /* CHEESY HACK: we assume that the header record immediately follows the
3732   node header.  This is because we need to know the node length to know where
3733   the record pointers are located, but we need to read the header record to
3734   know the node length. */
3735   err = mac_file_read(&BTref->fileref, sizeof(header_rec), &header_rec);
3736   if (err)
3737      return err;
3738
3739   BTref->nodeSize = get_UINT16BE(header_rec.nodeSize);
3740   BTref->rootNode = get_UINT32BE(header_rec.rootNode);
3741   BTref->firstLeafNode = get_UINT32BE(header_rec.firstLeafNode);
3742   BTref->attributes = get_UINT32BE(header_rec.attributes);
3743   BTref->treeDepth = get_UINT16BE(header_rec.treeDepth);
3744   BTref->maxKeyLength = get_UINT16BE(header_rec.maxKeyLength);
3745
3746   BTref->key_compare_func = key_compare_func;
3747
3748   BTref->node_buf = malloc(BTref->nodeSize);
3749   if (!BTref->node_buf)
3750      return IMGTOOLERR_OUTOFMEMORY;
3751
3752   if (BTREE_CHECKS)
3753   {
3754      /* optional: check integrity of B-tree */
3755      err = BT_check(BTref, is_extent);
3756      if (err)
3757         return err;
3758   }
3759
3760   return IMGTOOLERR_SUCCESS;
3761}
3762
3763/*
3764   BT_close
3765
3766   Close a B-tree
3767
3768   BTref (I/O): open B-tree file handle
3769*/
3770static void BT_close(mac_BTref *BTref)
3771{
3772   free(BTref->node_buf);
3773}
3774
3775/*
3776   BT_read_node
3777
3778   Read a node from a B-tree
3779
3780   BTref (I/O): open B-tree file handle
3781   node_ID (I): index of the node to read
3782   expected_kind (I): kind of the node to read
3783   expected_depth (I): depth of the node to read
3784   dest (O): destination buffer
3785
3786   Return imgtool error code
3787*/
3788static imgtoolerr_t BT_read_node(mac_BTref *BTref, UINT32 node_ID, int expected_kind, int expected_depth, void *dest)
3789{
3790   imgtoolerr_t err;
3791
3792   /* seek to node */
3793   err = mac_file_seek(&BTref->fileref, node_ID*BTref->nodeSize);
3794   if (err)
3795      return err;
3796
3797   /* read it */
3798   err = mac_file_read(&BTref->fileref, BTref->nodeSize, dest);
3799   if (err)
3800      return err;
3801
3802   /* check node kind and depth */
3803   if ((((BTNodeHeader *) dest)->kind != expected_kind)
3804         || (((BTNodeHeader *) dest)->height != expected_depth))
3805      return IMGTOOLERR_CORRUPTIMAGE;
3806
3807   return IMGTOOLERR_SUCCESS;
3808}
3809
3810/*
3811   BT_node_get_record
3812
3813   Extract a raw record from a B-tree node
3814
3815   BTref (I/O): open B-tree file handle
3816   node_buf (I): buffer with the node the record should be extracted from
3817   recnum (I): index of record to read
3818   rec_ptr (O): set to point to start of record (key + data)
3819   rec_len (O): set to total length of record (key + data)
3820
3821   Return imgtool error code
3822*/
3823static imgtoolerr_t BT_node_get_record(mac_BTref *BTref, void *node_buf, unsigned recnum, void **rec_ptr, int *rec_len)
3824{
3825   UINT16 node_numRecords = get_UINT16BE(((BTNodeHeader *) node_buf)->numRecords);
3826   UINT16 offset;
3827   UINT16 next_offset;
3828
3829   if (recnum >= node_numRecords)
3830      return IMGTOOLERR_UNEXPECTED;
3831
3832   offset = get_UINT16BE(((UINT16BE *)((UINT8 *) node_buf + BTref->nodeSize))[-recnum-1]);
3833   next_offset = get_UINT16BE(((UINT16BE *)((UINT8 *) node_buf + BTref->nodeSize))[-recnum-2]);
3834
3835   if ((offset < sizeof(BTNodeHeader)) || (offset > BTref->nodeSize-2*node_numRecords)
3836         || (next_offset < sizeof(BTNodeHeader)) || (next_offset > BTref->nodeSize-2*node_numRecords)
3837         || (offset & 1) || (next_offset & 1)
3838         || (offset > next_offset))
3839      return IMGTOOLERR_CORRUPTIMAGE;
3840
3841   *rec_ptr = (UINT8 *)node_buf + offset;
3842   *rec_len = next_offset - offset;
3843
3844   return IMGTOOLERR_SUCCESS;
3845}
3846
3847/*
3848   BT_node_get_keyed_record
3849
3850   Extract a keyed record from a B-tree node.  Equivalent to
3851   BT_node_get_record, only we do extra checks.
3852
3853   BTref (I/O): open B-tree file handle
3854   node_buf (I): buffer with the node the record should be extracted from
3855   node_is_index (I): TRUE if node is index node
3856   recnum (I): index of record to read
3857   rec_ptr (O): set to point to start of record (key + data)
3858   rec_len (O): set to total length of record (key + data)
3859
3860   Return imgtool error code
3861*/
3862static imgtoolerr_t BT_node_get_keyed_record(mac_BTref *BTref, void *node_buf, int node_is_index, unsigned recnum, void **rec_ptr, int *rec_len)
3863{
3864   imgtoolerr_t err;
3865   void *lrec_ptr;
3866   int lrec_len;
3867   int key_len;
3868
3869   /* extract record */
3870   err = BT_node_get_record(BTref, node_buf, recnum, &lrec_ptr, &lrec_len);
3871   if (err)
3872      return err;
3873
3874   /* read key len */
3875   key_len = (BTref->attributes & btha_bigKeysMask)
3876            ? get_UINT16BE(* (UINT16BE *)lrec_ptr)
3877            : (* (UINT8 *)lrec_ptr);
3878
3879   /* check that key fits in record */
3880   if ((key_len + ((BTref->attributes & btha_bigKeysMask) ? 2 : 1)) > lrec_len)
3881      /* hurk! */
3882      return IMGTOOLERR_CORRUPTIMAGE;
3883
3884   if (key_len > BTref->maxKeyLength)
3885      return IMGTOOLERR_CORRUPTIMAGE;
3886
3887   if (node_is_index && (! (BTref->attributes & btha_variableIndexKeysMask)) && (key_len != BTref->maxKeyLength))
3888      return IMGTOOLERR_CORRUPTIMAGE;
3889
3890   if (rec_ptr)
3891      *rec_ptr = lrec_ptr;
3892   if (rec_len)
3893      *rec_len = lrec_len;
3894
3895   return IMGTOOLERR_SUCCESS;
3896}
3897
3898/*
3899   BT_get_keyed_record_data
3900
3901   extract data from a keyed record
3902
3903   BTref (I/O): open B-tree file handle
3904   rec_ptr (I): point to start of record (key + data)
3905   rec_len (I): total length of record (key + data)
3906   data_ptr (O): set to point to record data
3907   data_len (O): set to length of record data
3908
3909   Return imgtool error code
3910*/
3911static imgtoolerr_t BT_get_keyed_record_data(mac_BTref *BTref, void *rec_ptr, int rec_len, void **data_ptr, int *data_len)
3912{
3913   int lkey_len;
3914   int data_offset;
3915
3916   /* read key len */
3917   lkey_len = (BTref->attributes & btha_bigKeysMask)
3918            ? get_UINT16BE(* (UINT16BE *)rec_ptr)
3919            : (* (UINT8 *)rec_ptr);
3920
3921   /* compute offset to data record */
3922   data_offset = lkey_len + ((BTref->attributes & btha_bigKeysMask) ? 2 : 1);
3923   if (data_offset > rec_len)
3924      /* hurk! */
3925      return IMGTOOLERR_CORRUPTIMAGE;
3926   /* fix alignment */
3927   if (data_offset & 1)
3928      data_offset++;
3929
3930   if (data_ptr)
3931      *data_ptr = (UINT8 *)rec_ptr + data_offset;
3932   if (data_len)
3933      *data_len = (rec_len > data_offset) ? rec_len-data_offset : 0;
3934
3935   return IMGTOOLERR_SUCCESS;
3936}
3937
3938/*
3939   BT_check
3940
3941   Check integrity of a complete B-tree
3942
3943   BTref (I/O): open B-tree file handle
3944   is_extent (I): TRUE if we are opening the extent B-tree (we want to do
3945      extra checks in this case because the extent B-Tree may include extent
3946      records for the extent B-tree itself, and if an extent record for the
3947      extent B-tree is located in an extent that has not been defined by
3948      previous extent records, then we can never retreive this extent record)
3949
3950   Return imgtool error code
3951*/
3952static imgtoolerr_t BT_check(mac_BTref *BTref, int is_extent)
3953{
3954   UINT16 node_numRecords;
3955   BTHeaderRecord *header_rec;
3956   UINT8 *bitmap;
3957   struct
3958   {
3959      void *buf;
3960      UINT32 node_num;
3961      UINT32 cur_rec;
3962      UINT32 num_recs;
3963   } *data_nodes;
3964   int i, j;
3965   UINT32 cur_node, prev_node;
3966   void *rec1, *rec2;
3967   int rec1_len, rec2_len;
3968   void *rec1_data;
3969   int rec1_data_len;
3970   UINT32 totalNodes, lastLeafNode;
3971   UINT32 freeNodes;
3972   int compare_result;
3973   UINT32 map_count, map_len;
3974   UINT32 run_len;
3975   UINT32 run_bit_len;
3976   UINT32 actualFreeNodes;
3977   imgtoolerr_t err;
3978   UINT32 maxExtentAB = 0, maxExtentNode = 0, extentEOL = 0;   /* if is_extent is TRUE */
3979
3980   if (is_extent)
3981   {
3982      switch (BTref->fileref.l2_img->format)
3983      {
3984      case L2I_MFS:
3985         /* MFS does not feature any extents B-tree! */
3986         return IMGTOOLERR_UNEXPECTED;
3987
3988      case L2I_HFS:
3989         maxExtentAB = 0;
3990         for (j=0; j<3; j++)
3991            maxExtentAB += get_UINT16BE(BTref->fileref.u.hfs.extents[j].numABlks);
3992         maxExtentNode = (UINT64)maxExtentAB * 512 * BTref->fileref.l2_img->blocksperAB
3993                              / BTref->nodeSize;
3994         extentEOL = FALSE;
3995         break;
3996      }
3997   }
3998
3999   /* read header node */
4000   if ((! is_extent) || (0 < maxExtentNode))
4001      err = BT_read_node(BTref, 0, btnk_headerNode, 0, BTref->node_buf);
4002   else
4003      err = IMGTOOLERR_CORRUPTIMAGE;
4004   if (err)
4005      return err;
4006
4007   /* check we have enough records */
4008   node_numRecords = get_UINT16BE(((BTNodeHeader *) BTref->node_buf)->numRecords);
4009   if (node_numRecords < 3)
4010      return IMGTOOLERR_CORRUPTIMAGE;
4011
4012   /* get header record */
4013   err = BT_node_get_record(BTref, BTref->node_buf, 0, &rec1, &rec1_len);
4014   if (err)
4015      return err;
4016   header_rec = (BTHeaderRecord *)rec1;
4017
4018   /* check length of header record */
4019   if (rec1_len < sizeof(BTHeaderRecord))
4020      return IMGTOOLERR_CORRUPTIMAGE;
4021
4022   totalNodes = get_UINT32BE(header_rec->totalNodes);
4023   if (totalNodes == 0)
4024      /* we need at least one header node */
4025      return IMGTOOLERR_CORRUPTIMAGE;
4026   lastLeafNode = get_UINT32BE(header_rec->lastLeafNode);
4027   freeNodes = get_UINT32BE(header_rec->freeNodes);
4028
4029   /* check file length */
4030   if ((BTref->nodeSize * totalNodes) > BTref->fileref.pLen)
4031      return IMGTOOLERR_CORRUPTIMAGE;
4032
4033   /* initialize for the function postlog ("bail:" tag) */
4034   err = IMGTOOLERR_SUCCESS;
4035   bitmap = NULL;
4036   data_nodes = NULL;
4037
4038   /* alloc buffer for reconstructed bitmap */
4039   map_len = (totalNodes + 7) / 8;
4040   bitmap = malloc(map_len);
4041   if (! bitmap)
4042      return IMGTOOLERR_OUTOFMEMORY;
4043   memset(bitmap, 0, map_len);
4044
4045   /* check B-tree data nodes (i.e. index and leaf nodes) */
4046   if (BTref->treeDepth == 0)
4047   {
4048      /* B-tree is empty */
4049      if (BTref->rootNode || BTref->firstLeafNode || lastLeafNode)
4050      {
4051         err = IMGTOOLERR_OUTOFMEMORY;
4052         goto bail;
4053      }
4054   }
4055   else
4056   {
4057      /* alloc array of buffers for catalog data nodes */
4058      data_nodes = malloc(sizeof(data_nodes[0]) * BTref->treeDepth);
4059      if (! data_nodes)
4060      {
4061         err = IMGTOOLERR_OUTOFMEMORY;
4062         goto bail;
4063      }
4064      for (i=0; i<BTref->treeDepth; i++)
4065         data_nodes[i].buf = NULL;   /* required for function postlog to work should next loop fail */
4066      for (i=0; i<BTref->treeDepth; i++)
4067      {
4068         data_nodes[i].buf = malloc(BTref->nodeSize);
4069         if (!data_nodes[i].buf)
4070         {
4071            err = IMGTOOLERR_OUTOFMEMORY;
4072            goto bail;
4073         }
4074      }
4075
4076      /* read first data nodes */
4077      cur_node = BTref->rootNode;
4078      for (i=BTref->treeDepth-1; i>=0; i--)
4079      {
4080         /* check node index */
4081         if (cur_node >= totalNodes)
4082         {
4083            err = IMGTOOLERR_CORRUPTIMAGE;
4084            goto bail;
4085         }
4086         /* check that node has not been used for another purpose */
4087         /* this check is unecessary because the current consistency checks
4088         that forward and back linking match and that node height is correct
4089         are enough to detect such errors */
4090         /*if (bitmap[cur_node >> 3] & (0x80 >> (cur_node & 7)))
4091         {
4092            err = IMGTOOLERR_CORRUPTIMAGE;
4093            goto bail;
4094         }*/
4095         /* add node in bitmap */
4096         bitmap[cur_node >> 3] |= (0x80 >> (cur_node & 7));
4097         /* read node */
4098         if ((! is_extent) || (cur_node < maxExtentNode))
4099            err = BT_read_node(BTref, cur_node, i ? btnk_indexNode : btnk_leafNode, i+1, data_nodes[i].buf);
4100         else
4101            err = IMGTOOLERR_CORRUPTIMAGE;
4102         if (err)
4103            goto bail;
4104         /* check that it is the first node at this level */
4105         if (get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->bLink))
4106         {
4107            err = IMGTOOLERR_CORRUPTIMAGE;
4108            goto bail;
4109         }
4110         /* fill other fields */
4111         data_nodes[i].node_num = cur_node;
4112         data_nodes[i].cur_rec = 0;
4113         data_nodes[i].num_recs = get_UINT16BE(((BTNodeHeader *) data_nodes[i].buf)->numRecords);
4114         /* check that there is at least one record */
4115         if (data_nodes[i].num_recs == 0)
4116         {
4117            err = IMGTOOLERR_CORRUPTIMAGE;
4118            goto bail;
4119         }
4120
4121         /* iterate to next level if applicable */
4122         if (i != 0)
4123         {
4124            /* extract first record */
4125            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, TRUE, 0, &rec1, &rec1_len);
4126            if (err)
4127               goto bail;
4128
4129            /* extract record data ptr */
4130            err = BT_get_keyed_record_data(BTref, rec1, rec1_len, &rec1_data, &rec1_data_len);
4131            if (err)
4132               goto bail;
4133            if (rec1_data_len < sizeof(UINT32BE))
4134            {
4135               err = IMGTOOLERR_CORRUPTIMAGE;
4136               goto bail;
4137            }
4138
4139            /* iterate to next level */
4140            cur_node = get_UINT32BE(* (UINT32BE *)rec1_data);
4141         }
4142      }
4143
4144      /* check that a) the root node has no successor, and b) that we have really
4145      read the first leaf node */
4146      if (get_UINT32BE(((BTNodeHeader *) data_nodes[BTref->treeDepth-1].buf)->fLink)
4147            || (cur_node != BTref->firstLeafNode))
4148      {
4149         err = IMGTOOLERR_CORRUPTIMAGE;
4150         goto bail;
4151      }
4152
4153      /* check that keys are ordered correctly */
4154      while (1)
4155      {
4156         /* iterate through parent nodes */
4157         i = 0;
4158         while ((i<BTref->treeDepth) && ((data_nodes[i].cur_rec == 0) || (data_nodes[i].cur_rec == data_nodes[i].num_recs)))
4159         {
4160            /* read next node if necessary */
4161            if (data_nodes[i].cur_rec == data_nodes[i].num_recs)
4162            {
4163               /* get link to next node */
4164               cur_node = get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->fLink);
4165               if (cur_node == 0)
4166               {
4167                  if (i == 0)
4168                     /* normal End of List */
4169                     goto end_of_list;
4170                  else
4171                  {
4172                     /* error */
4173                     err = IMGTOOLERR_CORRUPTIMAGE;
4174                     goto bail;
4175                  }
4176               }
4177               /* add node in bitmap */
4178               bitmap[cur_node >> 3] |= (0x80 >> (cur_node & 7));
4179               /* read node */
4180               if ((! is_extent) || (cur_node < maxExtentNode))
4181                  err = BT_read_node(BTref, cur_node, i ? btnk_indexNode : btnk_leafNode, i+1, data_nodes[i].buf);
4182               else
4183                  err = IMGTOOLERR_CORRUPTIMAGE;
4184               if (err)
4185                  goto bail;
4186               /* check that backward linking match forward linking */
4187               if (get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->bLink) != data_nodes[i].node_num)
4188               {
4189                  err = IMGTOOLERR_CORRUPTIMAGE;
4190                  goto bail;
4191               }
4192               /* fill other fields */
4193               data_nodes[i].node_num = cur_node;
4194               data_nodes[i].cur_rec = 0;
4195               data_nodes[i].num_recs = get_UINT16BE(((BTNodeHeader *) data_nodes[i].buf)->numRecords);
4196               /* check that there is at least one record */
4197               if (data_nodes[i].num_recs == 0)
4198               {
4199                  err = IMGTOOLERR_CORRUPTIMAGE;
4200                  goto bail;
4201               }
4202               /* next test is not necessary because we have checked that
4203               the root node has no successor */
4204               /*if (i < BTref->treeDepth-1)
4205               {*/
4206                  data_nodes[i+1].cur_rec++;
4207               /*}
4208               else
4209               {
4210                  err = IMGTOOLERR_CORRUPTIMAGE;
4211                  goto bail;
4212               }*/
4213            }
4214            i++;
4215         }
4216
4217         if (is_extent && !extentEOL)
4218         {
4219            /* extract current leaf record and update maxExtentAB and
4220            maxExtentNode */
4221            hfs_extentKey *extentKey;
4222            hfs_extent *extentData;
4223
4224            /* extract current leaf record */
4225            err = BT_node_get_keyed_record(BTref, data_nodes[0].buf, FALSE, data_nodes[0].cur_rec, &rec1, &rec1_len);
4226            if (err)
4227               goto bail;
4228
4229            extentKey = rec1;
4230            if ((extentKey->keyLength < 7) || (extentKey->forkType != 0) || (get_UINT32BE(extentKey->fileID) != 3)
4231                  || (get_UINT16BE(extentKey->startBlock) != maxExtentAB))
4232               /* the key is corrupt or does not concern the extent
4233               B-tree: set the extentEOL flag so that we stop looking for
4234               further extent records for the extent B-tree */
4235               extentEOL = TRUE;
4236            else
4237            {   /* this key concerns the extent B-tree: update maxExtentAB
4238               and maxExtentNode */
4239               /* extract record data ptr */
4240               err = BT_get_keyed_record_data(BTref, rec1, rec1_len, &rec1_data, &rec1_data_len);
4241               if (err)
4242                  goto bail;
4243               if (rec1_data_len < sizeof(hfs_extent)*3)
4244                  /* the record is corrupt: set the extentEOL flag so
4245                  that we stop looking for further extent records for the
4246                  extent B-tree */
4247                  extentEOL = TRUE;
4248               else
4249               {
4250                  extentData = rec1_data;
4251
4252                  for (j=0; j<3; j++)
4253                     maxExtentAB += get_UINT16BE(extentData[j].numABlks);
4254                  maxExtentNode = (UINT64)maxExtentAB * 512 * BTref->fileref.l2_img->blocksperAB
4255                                    / BTref->nodeSize;
4256               }
4257            }
4258            if (extentEOL)
4259            {
4260               /* check that the extent B-Tree has been defined entirely */
4261               if (maxExtentNode < totalNodes)
4262               {   /* no good */
4263                  err = IMGTOOLERR_CORRUPTIMAGE;
4264                  goto bail;
4265               }
4266            }
4267         }
4268
4269         if (i<BTref->treeDepth)
4270         {
4271            /* extract current record */
4272            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, i > 0, data_nodes[i].cur_rec, &rec1, &rec1_len);
4273            if (err)
4274               goto bail;
4275
4276            /* extract previous record */
4277            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, i > 0, data_nodes[i].cur_rec-1, &rec2, &rec2_len);
4278            if (err)
4279               goto bail;
4280
4281            /* check that it is sorted correctly */
4282            compare_result = (*BTref->key_compare_func)(rec1, rec2);
4283            if (compare_result <= 0)
4284            {
4285               err = IMGTOOLERR_CORRUPTIMAGE;
4286               goto bail;
4287            }
4288
4289            i--;
4290         }
4291         else
4292         {
4293            i--;
4294            if (i>0)
4295            {   /* extract first record of root if it is an index node */
4296               err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, TRUE, data_nodes[i].cur_rec, &rec1, &rec1_len);
4297               if (err)
4298                  goto bail;
4299            }
4300            i--;
4301         }
4302
4303         while (i>=0)
4304         {
4305            /* extract first record of current level */
4306            err = BT_node_get_keyed_record(BTref, data_nodes[i].buf, i > 0, data_nodes[i].cur_rec, &rec2, &rec2_len);
4307            if (err)
4308               goto bail;
4309
4310            /* compare key with key of current record of upper level */
4311            compare_result = (*BTref->key_compare_func)(rec1, rec2);
4312            if (compare_result != 0)
4313            {
4314               err = IMGTOOLERR_CORRUPTIMAGE;
4315               goto bail;
4316            }
4317
4318            /* extract record data ptr */
4319            err = BT_get_keyed_record_data(BTref, rec1, rec1_len, &rec1_data, &rec1_data_len);
4320            if (err)
4321               goto bail;
4322            if (rec1_data_len < sizeof(UINT32BE))
4323            {
4324               err = IMGTOOLERR_CORRUPTIMAGE;
4325               goto bail;
4326            }
4327            cur_node = get_UINT32BE(* (UINT32BE *)rec1_data);
4328
4329            /* compare node index with data of current record of upper
4330            level */
4331            if (cur_node != data_nodes[i].node_num)
4332            {
4333               err = IMGTOOLERR_CORRUPTIMAGE;
4334               goto bail;
4335            }
4336
4337            /* iterate to next level */
4338            rec1 = rec2;
4339            rec1_len = rec2_len;
4340            i--;
4341         }
4342
4343         /* next leaf record */
4344         data_nodes[0].cur_rec++;
4345      }
4346
4347end_of_list:
4348      /* check that we are at the end of list for each index level */
4349      for (i=1; i<BTref->treeDepth; i++)
4350      {
4351         if ((data_nodes[i].cur_rec != (data_nodes[i].num_recs-1))
4352               || get_UINT32BE(((BTNodeHeader *) data_nodes[i].buf)->fLink))
4353         {
4354            err = IMGTOOLERR_CORRUPTIMAGE;
4355            goto bail;
4356         }
4357      }
4358      /* check that the last leaf node is what it is expected to be */
4359      if (data_nodes[0].node_num != lastLeafNode)
4360      {
4361         err = IMGTOOLERR_CORRUPTIMAGE;
4362         goto bail;
4363      }
4364   }
4365
4366   /* check map node chain */
4367   cur_node = 0;   /* node 0 is the header node... */
4368   bitmap[0] |= 0x80;
4369   /* check back linking */
4370   if (get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->bLink))
4371   {
4372      err = IMGTOOLERR_CORRUPTIMAGE;
4373      goto bail;
4374   }
4375   /* get pointer to next node */
4376   cur_node = get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->fLink);
4377   while (cur_node != 0)
4378   {
4379      /* save node address */
4380      prev_node = cur_node;
4381      /* check that node has not been used for another purpose */
4382      /* this check is unecessary because the current consistency checks that
4383      forward and back linking match and that node height is correct are
4384      enough to detect such errors */
4385      /*if (bitmap[cur_node >> 3] & (0x80 >> (cur_node & 7)))
4386      {
4387         err = IMGTOOLERR_CORRUPTIMAGE;
4388         goto bail;
4389      }*/
4390      /* add node in bitmap */
4391      bitmap[cur_node >> 3] |= (0x80 >> (cur_node & 7));
4392      /* read map node */
4393      if ((! is_extent) || (cur_node < maxExtentNode))
4394         err = BT_read_node(BTref, cur_node, btnk_mapNode, 0, BTref->node_buf);
4395      else
4396         err = IMGTOOLERR_CORRUPTIMAGE;
4397      if (err)
4398         goto bail;
4399      /* check back linking */
4400      if (get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->bLink) != prev_node)
4401      {
4402         err = IMGTOOLERR_CORRUPTIMAGE;
4403         goto bail;
4404      }
4405      /* get pointer to next node */
4406      cur_node = get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->fLink);
4407   }
4408
4409   /* re-read header node */
4410   err = BT_read_node(BTref, 0, btnk_headerNode, 0, BTref->node_buf);
4411   if (err)
4412      goto bail;
4413
4414   /* get header bitmap record */
4415   err = BT_node_get_record(BTref, BTref->node_buf, 2, &rec1, &rec1_len);
4416   if (err)
4417      goto bail;
4418
4419   /* check bitmap, iterating map nodes */
4420   map_count = 0;
4421   actualFreeNodes = 0;
4422   while (map_count < map_len)
4423   {
4424      /* compute compare len */
4425      run_len = rec1_len;
4426      if (run_len > (map_len-map_count))
4427         run_len = map_len-map_count;
4428      /* check that all used nodes are marked as such in the B-tree bitmap */
4429      for (i=0; i<run_len; i++)
4430         if (bitmap[map_count+i] & ~((UINT8 *)rec1)[i])
4431         {
4432            err = IMGTOOLERR_CORRUPTIMAGE;
4433            goto bail;
4434         }
4435      /* count free nodes */
4436      run_bit_len = rec1_len*8;
4437      if (run_bit_len > (totalNodes-map_count*8))
4438         run_bit_len = totalNodes-map_count*8;
4439      for (i=0; i<run_bit_len; i++)
4440         if (! (((UINT8 *)rec1)[i>>3] & (0x80 >> (i & 7))))
4441            actualFreeNodes++;
4442      map_count += run_len;
4443      /* read next map node if required */
4444      if (map_count < map_len)
4445      {
4446         /* get pointer to next node */
4447         cur_node = get_UINT32BE(((BTNodeHeader *) BTref->node_buf)->fLink);
4448         if (cur_node == 0)
4449         {
4450            err = IMGTOOLERR_CORRUPTIMAGE;
4451            goto bail;
4452         }
4453         /* read map node */
4454         err = BT_read_node(BTref, cur_node, btnk_mapNode, 0, BTref->node_buf);
4455         if (err)
4456            goto bail;
4457         /* get map record */
4458         err = BT_node_get_record(BTref, BTref->node_buf, 0, &rec1, &rec1_len);
4459         if (err)
4460            goto bail;
4461         header_rec = (BTHeaderRecord *)rec1;
4462      }
4463   }
4464
4465   /* check free node count */
4466   if (freeNodes != actualFreeNodes)
4467      return IMGTOOLERR_CORRUPTIMAGE;
4468
4469bail:
4470   /* free buffers */
4471   if (data_nodes)
4472   {
4473      for (i=0; i<BTref->treeDepth; i++)
4474         if (data_nodes[i].buf)
4475            free(data_nodes[i].buf);
4476      free(data_nodes);
4477   }
4478   if (bitmap)
4479      free(bitmap);
4480
4481   return err;
4482}
4483
4484/*
4485   BT_search_leaf_rec
4486
4487   Search for a given key in a B-Tree.  If exact match found, returns
4488   corresponding leaf record.  Otherwise, may return the greatest record less
4489   than the requested key (of course, this will fail if the key is lower than
4490   all keys in the B-Tree).
4491
4492   BTref (I/O): open B-tree file handle
4493   search_key (I): key to search the B-Tree for
4494   node_ID (O): set to the node ID of the node the record is located in (may
4495      be NULL)
4496   record_ID (O): set to the index of the record in the node (may be NULL)
4497   record_ptr (O): set to point to record in node buffer (may be NULL)
4498   record_len (O): set to total record len (may be NULL)
4499   search_exact_match (I): if TRUE, the function will search for a record
4500      equal to search_key; if FALSE, the function will search for the
4501      greatest record less than or equal to search_key
4502   match_found (O): set to TRUE if an exact match for search_key has been
4503      found (only makes sense if search_exact_match is FALSE) (may be NULL)
4504
4505   Return imgtool error code
4506*/
4507static imgtoolerr_t BT_search_leaf_rec(mac_BTref *BTref, const void *search_key,
4508                              UINT32 *node_ID, int *record_ID,
4509                              void **record_ptr, int *record_len,
4510                              int search_exact_match, int *match_found)
4511{
4512   imgtoolerr_t err;
4513   int i;
4514   UINT32 cur_node;
4515   void *cur_rec;
4516   int cur_rec_len;
4517   void *last_rec;
4518   int last_rec_len = 0;
4519   void *rec_data;
4520   int rec_data_len;
4521   int depth;
4522   UINT16 node_numRecords;
4523   int compare_result = 0;
4524
4525   /* start with root node */
4526   if ((BTref->rootNode == 0) || (BTref->treeDepth == 0))
4527      /* tree is empty */
4528      return ((BTref->rootNode == 0) == (BTref->treeDepth == 0))
4529               ? IMGTOOLERR_FILENOTFOUND
4530               : IMGTOOLERR_CORRUPTIMAGE;
4531
4532   cur_node = BTref->rootNode;
4533   depth = BTref->treeDepth;
4534
4535   while (1)
4536   {
4537      /* read current node */
4538      err = BT_read_node(BTref, cur_node, (depth > 1) ? btnk_indexNode : btnk_leafNode, depth, BTref->node_buf);
4539      if (err)
4540         return err;
4541
4542      /* search for key */
4543      node_numRecords = get_UINT16BE(((BTNodeHeader *) BTref->node_buf)->numRecords);
4544      last_rec = cur_rec = NULL;
4545      for (i=0; i<node_numRecords; i++)
4546      {
4547         err = BT_node_get_keyed_record(BTref, BTref->node_buf, depth > 1, i, &cur_rec, &cur_rec_len);
4548         if (err)
4549            return err;
4550
4551         compare_result = (*BTref->key_compare_func)(cur_rec, search_key);
4552         if (compare_result > 0)
4553            break;
4554         last_rec = cur_rec;
4555         last_rec_len = cur_rec_len;
4556         if (compare_result == 0)
4557            break;
4558      }
4559
4560      if (! last_rec)
4561      {   /* all keys are greater than the search key: the search key is
4562         nowhere in the tree */
4563         if (search_exact_match)
4564            return IMGTOOLERR_FILENOTFOUND;
4565
4566         if (match_found)
4567            *match_found = FALSE;
4568
4569         if (node_ID)
4570            *node_ID = 0;
4571
4572         if (record_ID)
4573            *record_ID = -1;
4574
4575         if (record_ptr)
4576            *record_ptr = NULL;
4577
4578         return IMGTOOLERR_SUCCESS;
4579      }
4580
4581      if (((BTNodeHeader *) BTref->node_buf)->kind == btnk_leafNode)
4582         /* leaf node -> end of search */
4583         break;
4584
4585      /* extract record data ptr */
4586      err = BT_get_keyed_record_data(BTref, last_rec, last_rec_len, &rec_data, &rec_data_len);
4587      if (err)
4588         return err;
4589      if (rec_data_len < sizeof(UINT32BE))
4590         return IMGTOOLERR_CORRUPTIMAGE;
4591
4592      /* iterate to next level */
4593      cur_node = get_UINT32BE(* (UINT32BE *)rec_data);
4594      depth--;
4595   }
4596
4597   if (compare_result != 0)
4598      /* key not found */
4599      if (search_exact_match)
4600         return IMGTOOLERR_FILENOTFOUND;
4601
4602   if (match_found)
4603      *match_found = (compare_result == 0);
4604
4605   if (node_ID)
4606      *node_ID = cur_node;
4607
4608   if (record_ID)
4609      *record_ID = i;
4610
4611   if (record_ptr)
4612      *record_ptr = last_rec;
4613
4614   if (record_len)
4615      *record_len = last_rec_len;
4616
4617   return IMGTOOLERR_SUCCESS;
4618}
4619
4620/*
4621   BT_leaf_rec_enumerator_open
4622
4623   Open enumerator for leaf records of a B-Tree
4624
4625   BTref (I/O): open B-tree file handle
4626   enumerator (O): B-Tree enumerator to open
4627
4628   Return imgtool error code
4629*/
4630static imgtoolerr_t BT_leaf_rec_enumerator_open(mac_BTref *BTref, BT_leaf_rec_enumerator *enumerator)
4631{
4632   enumerator->BTref = BTref;
4633   enumerator->cur_node = BTref->firstLeafNode;
4634   enumerator->cur_rec = 0;
4635
4636   return IMGTOOLERR_SUCCESS;
4637}
4638
4639/*
4640   BT_leaf_rec_enumerator_read
4641
4642   Read next leaf record of a B-Tree
4643
4644   enumerator (I/O): open B-Tree enumerator
4645
4646   Return imgtool error code
4647*/
4648static imgtoolerr_t BT_leaf_rec_enumerator_read(BT_leaf_rec_enumerator *enumerator, void **record_ptr, int *rec_len)
4649{
4650   UINT16 node_numRecords;
4651   imgtoolerr_t err;
4652
4653
4654   *record_ptr = NULL;
4655
4656   /* check EOList condition */
4657   if (enumerator->cur_node == 0)
4658      return IMGTOOLERR_SUCCESS;
4659
4660   /* read current node */
4661   err = BT_read_node(enumerator->BTref, enumerator->cur_node, btnk_leafNode, 1, enumerator->BTref->node_buf);
4662   if (err)
4663      return err;
4664   node_numRecords = get_UINT16BE(((BTNodeHeader *) enumerator->BTref->node_buf)->numRecords);
4665
4666   /* skip nodes until we find a record */
4667   while ((enumerator->cur_rec >= node_numRecords) && (enumerator->cur_node != 0))
4668   {
4669      enumerator->cur_node = get_UINT32BE(((BTNodeHeader *) enumerator->BTref->node_buf)->fLink);
4670      enumerator->cur_rec = 0;
4671
4672      /* read node */
4673      err = BT_read_node(enumerator->BTref, enumerator->cur_node, btnk_leafNode, 1, enumerator->BTref->node_buf);
4674      if (err)
4675         return err;
4676      node_numRecords = get_UINT16BE(((BTNodeHeader *) enumerator->BTref->node_buf)->numRecords);
4677   }
4678
4679   /* check EOList condition */
4680   if (enumerator->cur_node == 0)
4681      return IMGTOOLERR_SUCCESS;
4682
4683   /* get current record */
4684   err = BT_node_get_keyed_record(enumerator->BTref, enumerator->BTref->node_buf, FALSE, enumerator->cur_rec, record_ptr, rec_len);
4685   if (err)
4686      return err;
4687
4688   /* iterate to next record */
4689   enumerator->cur_rec++;
4690   if (enumerator->cur_rec >= node_numRecords)
4691   {   /* iterate to next node if last record (not required, but will improve
4692      performance on next iteration) */
4693      enumerator->cur_node = get_UINT32BE(((BTNodeHeader *) enumerator->BTref->node_buf)->fLink);
4694      enumerator->cur_rec = 0;
4695   }
4696   return IMGTOOLERR_SUCCESS;
4697}
4698
4699/*
4700   B-Tree extend EOF algorithm:
4701   * see if the bitmap will need to be extended
4702   * extend EOF by min 1 (if bitmap is large engough) or 2 (if bitmap needs
4703      to be extended) and max ClumpSiz (see extClpSiz and ctClpSiz in MDB)
4704      ***If we are extending the extent B-Tree, we need to defer the possible
4705      creation of an additional extent record, or we might enter an endless
4706      recursion loop***
4707
4708   Empty node alloc algorithm:
4709
4710   * see if there is any free node in B-tree bitmap
4711   * optionally, try to compact the B-tree if file is full
4712   * if file is still full, extend EOF and try again
4713   * mark new block as used and return its index
4714
4715
4716   Empty node delete algorithm:
4717
4718   * remove node from link list
4719   * mark node as free in the B-tree bitmap
4720   * optionally, if more than N% of the B-tree is free, compact the B-tree and
4721      free some disk space
4722   * Count nodes on this level; if there is only one left, delete parent index
4723      node and mark the relaining node as root; if it was the last leaf node,
4724      update header node with an empty B-tree; in either case, decrement tree
4725      depth
4726
4727
4728   Record shifting algorithm:
4729
4730   For a given node and its first non-empty successor node:
4731
4732   * compute how much free room there is in the node
4733   * see if the first record of the first non-empty successor can fit
4734   * if so, move it (i.e. delete the first record of the later node, and add a
4735      copy of it to the end of the former)
4736
4737
4738   Node merging algorithm
4739
4740   * Consider node and its predecessor.  If there is room, shift all records
4741      from later to former, then delete empty later node, and delete later
4742      record from parent index node.
4743
4744
4745   Node splitting algorithm (non-first)
4746
4747   * Consider node and its predecessor.  Create new middle node and split
4748      records in 3 even sets.  Update record for last node and insert record
4749      for middle node in parent index node.
4750
4751
4752   Node splitting algorithm (first node)
4753
4754   * Create new successor node, and split records in 2 1/3 and 2/3 sets.
4755      Insert record for later node in parent index node.
4756
4757
4758   Record delete algorithm:
4759
4760   * remove record from node
4761   * if record was first in node, test if node is now empty
4762      * if node is not empty, substitute key of deleted record with key of
4763         new head record in index tree
4764      * if node is empty, delete key of deleted record in index tree, then
4765         delete empty node
4766   * optionally, look the predecessor node.  Merge the two nodes if possible.
4767
4768
4769   Record insert algorithm:
4770
4771   * if there room, just insert new record in node; if new record is in first
4772      position, update record in parent index node
4773   * else consider predecessor: see if we can make enough room by shifting
4774      records.  If so, do shift records, insert new record, update record in
4775      parent index node
4776   * else split the nodes and insert record
4777*/
4778/*
4779   Possible additions:
4780
4781   Node compaction algorithm:
4782
4783   This algorithm can be executed with a specific start point and max number
4784   of nodes, or with all nodes on a level.
4785
4786   * see how many nodes we can save by shifting records left
4787   * if we will save at least one node, do shift as many records as possible
4788      (try to leave free space split homogeneously???)
4789*/
4790
4791/*static void*/
4792
4793#if 0
4794#pragma mark -
4795#pragma mark RESOURCE IMPLEMENTATION
4796#endif
4797
4798/*
4799   Resource manager
4800
4801   The resource manager stores arbitrary chunks of data (resource) identified
4802   by a type/id pair.  The resource type is a 4-char code, which generally
4803   implies the format of the data (e.g. 'PICT' is for a quickdraw picture,
4804   'STR ' for a macintosh string, 'CODE' for 68k machine code, etc).  The
4805   resource id is a signed 16-bit number that uniquely identifies each
4806   resource of a given type.  Note that, with most resource types, resources
4807   with id < 128 are system resources that are available to all applications,
4808   whereas resources with id >= 128 are application resources visible only to
4809   the application that defines them.
4810
4811   Each resource can optionally have a resource name, which is a macintosh
4812   string of 255 chars at most.
4813
4814   Limits:
4815   16MBytes of data
4816   64kbytes of type+reference lists
4817   64kbytes of resource names
4818
4819   The Macintosh toolbox can open several resource files simulteanously to
4820   overcome these restrictions.
4821
4822   Resources are used virtually everywhere in the Macintosh Toolbox, so it is
4823   no surprise that file comments and MFS folders are stored in resource files.
4824*/
4825
4826/*
4827   Resource header
4828*/
4829typedef struct rsrc_header
4830{
4831   UINT32BE data_offs;      /* Offset from beginning of resource fork to resource data */
4832   UINT32BE map_offs;      /* Offset from beginning of resource fork to resource map */
4833   UINT32BE data_len;      /* Length of resource data */
4834   UINT32BE map_len;      /* Length of resource map */
4835} rsrc_header;
4836
4837/*
4838   Resource data: each data entry is preceded by its len (UINT32BE)
4839   Offset to specific data fields are gotten from the resource map
4840*/
4841
4842/*
4843   Resource map:
4844*/
4845typedef struct rsrc_map_header
4846{
4847   rsrc_header reserved0;   /* Reserved for copy of resource header */
4848   UINT32BE reserved1;      /* Reserved for handle to next resource map */
4849   UINT16BE reserved2;      /* Reserved for file reference number */
4850
4851   UINT16BE attr;         /* Resource fork attributes */
4852   UINT16BE typelist_offs;   /* Offset from beginning of map to resource type list */
4853   UINT16BE namelist_offs;   /* Offset from beginning of map to resource name list */
4854   UINT16BE type_count;   /* Number of types in the map minus 1 */
4855                     /* This is actually part of the type list, which matters for offsets */
4856} rsrc_map_header;
4857
4858/*
4859   Resource type list entry
4860*/
4861typedef struct rsrc_type_entry
4862{
4863   UINT32BE type;         /* Resource type */
4864   UINT16BE ref_count;      /* Number of resources of this type in map minus 1 */
4865   UINT16BE ref_offs;      /* Offset from beginning of resource type list to reference list for this type */
4866} rsrc_type_entry;
4867
4868/*
4869   Resource reference list entry
4870*/
4871typedef struct rsrc_ref_entry
4872{
4873   UINT16BE id;         /* Resource ID */
4874   UINT16BE name_offs;      /* Offset from beginning of resource name list to resource name */
4875                     /* (-1 if none) */
4876   UINT8 attr;            /* Resource attributes */
4877   UINT24BE data_offs;      /* Offset from beginning of resource data to data for this resource */
4878   UINT32BE reserved;      /* Reserved for handle to resource */
4879} rsrc_ref_entry;
4880
4881/*
4882   Resource name list entry: this is just a standard macintosh string
4883*/
4884
4885typedef struct mac_resfileref
4886{
4887   mac_fileref fileref;   /* open resource fork ref (you may open resources
4888                        files in data fork, too, if you ever need to,
4889                        but Classic MacOS never does such a thing
4890                        (MacOS X often does so, though)) */
4891   UINT32 data_offs;      /* Offset from beginning of resource file to resource data */
4892   UINT32 map_offs;      /* Offset from beginning of resource file to resource data */
4893
4894   UINT16 typelist_offs;   /* Offset from beginning of map to resource type list */
4895   UINT16 namelist_offs;   /* Offset from beginning of map to resource name list */
4896   UINT16 type_count;      /* Number of types in the map minus 1 */
4897                     /* This is actually part of the type list, which matters for offsets */
4898} mac_resfileref;
4899
4900#ifdef UNUSED_FUNCTION
4901/*
4902   resfile_open
4903
4904   Open a file as a resource file.  The file must be already open as a
4905   macintosh file.
4906
4907   resfileref (I/O): resource file handle to open (resfileref->fileref must
4908      have been opened previously)
4909
4910   Return imgtool error code
4911*/
4912static imgtoolerr_t resfile_open(mac_resfileref *resfileref)
4913{
4914   imgtoolerr_t err;
4915   rsrc_header header;
4916   rsrc_map_header map_header;
4917
4918   /* seek to resource header */
4919   err = mac_file_seek(&resfileref->fileref, 0);
4920   if (err)
4921      return err;
4922
4923   err = mac_file_read(&resfileref->fileref, sizeof(header), &header);
4924   if (err)
4925      return err;
4926
4927   resfileref->data_offs = get_UINT32BE(header.data_offs);
4928   resfileref->map_offs = get_UINT32BE(header.map_offs);
4929
4930   /* seek to resource map header */
4931   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs);
4932   if (err)
4933      return err;
4934
4935   err = mac_file_read(&resfileref->fileref, sizeof(map_header), &map_header);
4936   if (err)
4937      return err;
4938
4939   resfileref->typelist_offs = get_UINT16BE(map_header.typelist_offs);
4940   resfileref->namelist_offs = get_UINT16BE(map_header.namelist_offs);
4941   resfileref->type_count = get_UINT16BE(map_header.type_count);
4942
4943   return IMGTOOLERR_SUCCESS;
4944}
4945
4946/*
4947   resfile_get_entry
4948
4949   Get the resource entry in the resource map associated with a given type/id
4950   pair.
4951
4952   resfileref (I/O): open resource file handle
4953   type (I): type of the resource
4954   id (I): id of the resource
4955   entry (O): resource entry that has been read
4956
4957   Return imgtool error code
4958*/
4959static imgtoolerr_t resfile_get_entry(mac_resfileref *resfileref, UINT32 type, UINT16 id, rsrc_ref_entry *entry)
4960{
4961   imgtoolerr_t err;
4962   rsrc_type_entry type_entry;
4963   UINT16 ref_count;
4964   int i;
4965
4966   /* seek to resource type list in resource map */
4967   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs+resfileref->typelist_offs+2);
4968   if (err)
4969      return err;
4970
4971   if (resfileref->type_count == 0xffff)
4972      /* type list is empty */
4973      return IMGTOOLERR_FILENOTFOUND;
4974
4975   for (i=0; i<=resfileref->type_count; i++)
4976   {
4977      err = mac_file_read(&resfileref->fileref, sizeof(type_entry), &type_entry);
4978      if (err)
4979         return err;
4980      if (type == get_UINT32BE(type_entry.type))
4981         break;
4982   }
4983   if (i > resfileref->type_count)
4984      /* type not found in list */
4985      return IMGTOOLERR_FILENOTFOUND;
4986
4987   ref_count = get_UINT16BE(type_entry.ref_count);
4988
4989   /* seek to resource ref list for this type in resource map */
4990   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs+resfileref->typelist_offs+get_UINT16BE(type_entry.ref_offs));
4991   if (err)
4992      return err;
4993
4994   if (ref_count == 0xffff)
4995      /* ref list is empty */
4996      return IMGTOOLERR_FILENOTFOUND;
4997
4998   for (i=0; i<=ref_count; i++)
4999   {
5000      err = mac_file_read(&resfileref->fileref, sizeof(*entry), entry);
5001      if (err)
5002         return err;
5003      if (id == get_UINT16BE(entry->id))
5004         break;
5005   }
5006   if (i > ref_count)
5007      /* id not found in list */
5008      return IMGTOOLERR_FILENOTFOUND;
5009
5010   /* type+id have been found... */
5011   return IMGTOOLERR_SUCCESS;
5012}
5013
5014/*
5015   resfile_get_resname
5016
5017   Get the name of a resource.
5018
5019   resfileref (I/O): open resource file handle
5020   entry (I): resource entry in the resource map (returned by
5021      resfile_get_entry)
5022   string (O): resource name
5023
5024   Return imgtool error code
5025*/
5026static imgtoolerr_t resfile_get_resname(mac_resfileref *resfileref, const rsrc_ref_entry *entry, mac_str255 string)
5027{
5028   imgtoolerr_t err;
5029   UINT16 name_offs;
5030   UINT8 len;
5031
5032   name_offs = get_UINT16BE(entry->name_offs);
5033
5034   if (name_offs == 0xffff)
5035      /* ref list is empty */
5036      return IMGTOOLERR_UNEXPECTED;
5037
5038   /* seek to resource name in name list in resource map */
5039   err = mac_file_seek(&resfileref->fileref, resfileref->map_offs+name_offs);
5040   if (err)
5041      return err;
5042
5043   /* get string length */
5044   err = mac_file_read(&resfileref->fileref, 1, &len);
5045   if (err)
5046      return err;
5047
5048   string[0] = len;
5049
5050   /* get string data */
5051   err = mac_file_read(&resfileref->fileref, len, string+1);
5052   if (err)
5053      return err;
5054
5055   return IMGTOOLERR_SUCCESS;
5056}
5057
5058/*
5059   resfile_get_reslen
5060
5061   Get the data length for a given resource.
5062
5063   resfileref (I/O): open resource file handle
5064   entry (I): resource entry in the resource map (returned by
5065      resfile_get_entry)
5066   len (O): resource length
5067
5068   Return imgtool error code
5069*/
5070static imgtoolerr_t resfile_get_reslen(mac_resfileref *resfileref, const rsrc_ref_entry *entry, UINT32 *len)
5071{
5072   imgtoolerr_t err;
5073   UINT32 data_offs;
5074   UINT32BE llen;
5075
5076   data_offs = get_UINT24BE(entry->data_offs);
5077
5078   /* seek to resource data in resource data section */
5079   err = mac_file_seek(&resfileref->fileref, resfileref->data_offs+data_offs);
5080   if (err)
5081      return err;
5082
5083   /* get data length */
5084   err = mac_file_read(&resfileref->fileref, sizeof(llen), &llen);
5085   if (err)
5086      return err;
5087
5088   *len = get_UINT32BE(llen);
5089
5090   return IMGTOOLERR_SUCCESS;
5091}
5092
5093/*
5094   resfile_get_resdata
5095
5096   Get the data for a given resource.
5097
5098   resfileref (I/O): open resource file handle
5099   entry (I): resource entry in the resource map (returned by
5100      resfile_get_entry)
5101   offset (I): offset the data should be read from, usually 0
5102   len (I): length of the data to read, usually the value returned by
5103      resfile_get_reslen
5104   dest (O): resource data
5105
5106   Return imgtool error code
5107*/
5108static imgtoolerr_t resfile_get_resdata(mac_resfileref *resfileref, const rsrc_ref_entry *entry, UINT32 offset, UINT32 len, void *dest)
5109{
5110   imgtoolerr_t err;
5111   UINT32 data_offs;
5112   UINT32BE llen;
5113
5114   data_offs = get_UINT24BE(entry->data_offs);
5115
5116   /* seek to resource data in resource data section */
5117   err = mac_file_seek(&resfileref->fileref, resfileref->data_offs+data_offs);
5118   if (err)
5119      return err;
5120
5121   /* get data length */
5122   err = mac_file_read(&resfileref->fileref, sizeof(llen), &llen);
5123   if (err)
5124      return err;
5125
5126   /* check that we do not ask to read more data than avalaible */
5127   if ((offset + len) > get_UINT32BE(llen))
5128      return IMGTOOLERR_UNEXPECTED;
5129
5130   if (offset)
5131   {   /* seek to resource data offset in resource data section */
5132      err = mac_file_seek(&resfileref->fileref, resfileref->data_offs+data_offs+4+offset);
5133      if (err)
5134         return err;
5135   }
5136
5137   /* get data */
5138   err = mac_file_read(&resfileref->fileref, len, dest);
5139   if (err)
5140      return err;
5141
5142   return IMGTOOLERR_SUCCESS;
5143}
5144#endif
5145
5146#if 0
5147#pragma mark -
5148#pragma mark DESKTOP FILE IMPLEMENTATION
5149#endif
5150/*
5151   All macintosh volumes have information stored in the desktop file or the
5152   desktop database.
5153
5154   Such information include file comments, copy of BNDL and FREF resources
5155   that describes supported file types for each application on the volume,
5156   copy of icons for each file type registered by each application on the
5157   volume, etc.  On MFS volumes, the list of folders is stored in the desktop
5158   file as well.
5159
5160
5161   There have been two implementations of the desktop metadata:
5162
5163   * The original desktop file.  The database is stored in the resource fork
5164      of a (usually invisible) file called "Desktop" (case may change
5165      according to system versions), located at the root of the volume.  The
5166      desktop file is used by System 6 and earlier for all volumes (unless
5167      Appleshare 2 is installed and the volume is shared IIRC), and by System
5168      7 and later for volumes smaller than 2MBytes (so that floppy disks
5169      remain fully compatible with earlier versions of system).  The desktop
5170      file is incompletely documented by Apple technote TB06.
5171
5172   * The desktop database.  The database is stored in the resource fork is
5173      stored in the data fork of two (usually invisible) files called
5174      "Desktop DF" and "Desktop DF".  The desktop database is used for
5175      volumes shared by Appleshare 2, and for most volumes under System 7 and
5176      later.  The format of these file is not documented AFAIK.
5177
5178
5179   The reasons for the introduction of the desktop database were:
5180   * the macintosh resource manager cannot share resource files, which was
5181      a problem for Appleshare
5182   * the macintosh resource manager is pretty limited (+/-16MByte of data and
5183      2727 resources at most), which was a problem for large hard disks with
5184      many programs/comments
5185*/
5186
5187#ifdef UNUSED_FUNCTION
5188/*
5189   get_comment
5190
5191   Get a comment from the Desktop file
5192
5193   l2_img (I): macintosh image the data should be read from
5194   id (I): comment id (from mfs_hashString(), or HFS FXInfo/DXInfo records)
5195   comment (O): comment that has been read
5196
5197   Return imgtool error code
5198*/
5199static imgtoolerr_t get_comment(mac_l2_imgref *l2_img, UINT16 id, mac_str255 comment)
5200{
5201   static const UINT8 desktop_fname[] = {'\7','D','e','s','k','t','o','p'};
5202   #define restype_FCMT (('F' << 24) | ('C' << 16) | ('M' << 8) | 'T')
5203   mac_resfileref resfileref;
5204   rsrc_ref_entry resentry;
5205   UINT32 reslen;
5206   imgtoolerr_t err;
5207
5208   /* open rsrc fork of file Desktop in root directory */
5209   err = mac_file_open(l2_img, 2, desktop_fname, rsrc_fork, &resfileref.fileref);
5210   if (err)
5211      return err;
5212
5213   /* open resource structures */
5214   err = resfile_open(&resfileref);
5215   if (err)
5216      return err;
5217
5218   /* look for resource FCMT #id */
5219   err = resfile_get_entry(&resfileref, restype_FCMT, id, &resentry);
5220   if (err)
5221      return err;
5222
5223   /* extract comment len */
5224   err = resfile_get_reslen(&resfileref, &resentry, &reslen);
5225   if (err)
5226      return err;
5227
5228   /* check comment len */
5229   if (reslen > 256)
5230      /* hurk */
5231      /*return IMGTOOLERR_CORRUPTIMAGE;*/
5232      /* people willing to extend the MFM comment field (you know, the kind
5233      of masochists that try to support 20-year-old OSes) might append extra
5234      fields, so we just truncate the resource */
5235      reslen = 256;
5236
5237   /* extract comment data */
5238   err = resfile_get_resdata(&resfileref, &resentry, 0, reslen, comment);
5239   if (err)
5240      return err;
5241
5242   /* phew, we are done! */
5243   return IMGTOOLERR_SUCCESS;
5244}
5245#endif
5246
5247#if 0
5248#pragma mark -
5249#pragma mark IMGTOOL MODULE IMPLEMENTATION
5250#endif
5251
5252#ifdef UNUSED_FUNCTION
5253static void mac_image_exit(imgtool_image *img);
5254#endif
5255static void mac_image_info(imgtool_image *img, char *string, size_t len);
5256static imgtoolerr_t mac_image_beginenum(imgtool_directory *enumeration, const char *path);
5257static imgtoolerr_t mac_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
5258static imgtoolerr_t mac_image_freespace(imgtool_partition *partition, UINT64 *size);
5259static imgtoolerr_t mac_image_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf);
5260static imgtoolerr_t mac_image_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions);
5261
5262#ifdef UNUSED_FUNCTION
5263/*
5264   close a mfs/hfs image
5265*/
5266static void mac_image_exit(imgtool_image *img)
5267{
5268   mac_l2_imgref *image = get_imgref(img);
5269
5270   mac_image_close(image);
5271}
5272#endif
5273
5274/*
5275   get basic information on a mfs/hfs image
5276
5277   Currently returns the volume name
5278*/
5279static void mac_image_info(imgtool_image *img, char *string, size_t len)
5280{
5281   mac_l2_imgref *image = get_imgref(img);
5282
5283   switch (image->format)
5284   {
5285   case L2I_MFS:
5286      mac_to_c_strncpy(string, len, image->u.mfs.volname);
5287      break;
5288
5289   case L2I_HFS:
5290      mac_to_c_strncpy(string, len, image->u.hfs.volname);
5291      break;
5292   }
5293}
5294
5295/*
5296   MFS/HFS catalog iterator, used when imgtool reads the catalog
5297*/
5298typedef struct mac_iterator
5299{
5300   mac_format format;
5301   mac_l2_imgref *l2_img;
5302   union
5303   {
5304      struct
5305      {
5306         mfs_dirref dirref;            /* open directory reference */
5307      } mfs;
5308      struct
5309      {
5310         hfs_cat_enumerator catref;      /* catalog file enumerator */
5311      } hfs;
5312   } u;
5313} mac_iterator;
5314
5315/*
5316   Open the disk catalog for enumeration
5317*/
5318static imgtoolerr_t mac_image_beginenum(imgtool_directory *enumeration, const char *path)
5319{
5320   mac_l2_imgref *image = get_imgref(imgtool_directory_image(enumeration));
5321   mac_iterator *iter = (mac_iterator *) imgtool_directory_extrabytes(enumeration);
5322   imgtoolerr_t err = IMGTOOLERR_UNEXPECTED;
5323
5324   iter->format = image->format;
5325   iter->l2_img = image;
5326
5327   switch (iter->format)
5328   {
5329   case L2I_MFS:
5330      err = mfs_dir_open(image, path, &iter->u.mfs.dirref);
5331      break;
5332
5333   case L2I_HFS:
5334      err = hfs_cat_open(image, path, &iter->u.hfs.catref);
5335      break;
5336   }
5337
5338   if (err)
5339      return err;
5340
5341   return IMGTOOLERR_SUCCESS;
5342}
5343
5344/*
5345   Enumerate disk catalog next entry (MFS)
5346*/
5347static imgtoolerr_t mfs_image_nextenum(mac_iterator *iter, imgtool_dirent *ent)
5348{
5349   mfs_dir_entry *cur_dir_entry;
5350   imgtoolerr_t err;
5351
5352
5353   assert(iter->format == L2I_MFS);
5354
5355   ent->corrupt = 0;
5356   ent->eof = 0;
5357
5358   err = mfs_dir_read(&iter->u.mfs.dirref, &cur_dir_entry);
5359   if (err)
5360   {
5361      /* error */
5362      ent->corrupt = 1;
5363      return err;
5364   }
5365   else if (!cur_dir_entry)
5366   {
5367      /* EOF */
5368      ent->eof = 1;
5369      return IMGTOOLERR_SUCCESS;
5370   }
5371
5372   /* copy info */
5373   mac_to_c_strncpy(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), cur_dir_entry->name);
5374   ent->filesize = get_UINT32BE(cur_dir_entry->dataPhysicalSize)
5375                  + get_UINT32BE(cur_dir_entry->rsrcPhysicalSize);
5376
5377   return IMGTOOLERR_SUCCESS;
5378}
5379
5380#if 0
5381/*
5382   Concatenate path elements in the reverse order
5383
5384   dest (O): destination buffer
5385   dest_cur_pos (I/O): current position in destination buffer (buffer is
5386      filled from end to start)
5387   dest_max_len (I): length of destination buffer (use length minus one if you
5388      want to preserve a trailing NUL character)
5389   src (I): source C string
5390*/
5391static void concat_fname(char *dest, int *dest_cur_pos, int dest_max_len, const char *src)
5392{
5393   static const char ellipsis[] = { '.', '.', '.' };
5394   int src_len = strlen(src);   /* number of chars from src to insert */
5395
5396   if (src_len <= *dest_cur_pos)
5397   {
5398      *dest_cur_pos -= src_len;
5399      memcpy(dest + *dest_cur_pos, src, src_len);
5400   }
5401   else
5402   {
5403      memcpy(dest, src + src_len - *dest_cur_pos, *dest_cur_pos);
5404      *dest_cur_pos = 0;
5405      memcpy(dest, ellipsis, (sizeof(ellipsis) <= dest_max_len)
5406                              ? sizeof(ellipsis)
5407                              : dest_max_len);
5408   }
5409}
5410#endif
5411
5412/*
5413   Enumerate disk catalog next entry (HFS)
5414*/
5415static imgtoolerr_t hfs_image_nextenum(mac_iterator *iter, imgtool_dirent *ent)
5416{
5417   hfs_catKey *catrec_key;
5418   hfs_catData *catrec_data;
5419   UINT16 dataRecType;
5420   imgtoolerr_t err;
5421   /* currently, the mac->C conversion transcodes one mac char with at most 3
5422   C chars */
5423   int cur_name_head;
5424
5425   assert(iter->format == L2I_HFS);
5426
5427   ent->corrupt = 0;
5428   ent->eof = 0;
5429
5430   do
5431   {
5432      err = hfs_cat_read(&iter->u.hfs.catref, &catrec_key, &catrec_data);
5433      if (err)
5434      {
5435         /* error */
5436         ent->corrupt = 1;
5437         return err;
5438      }
5439      else if (!catrec_key)
5440      {
5441         /* EOF */
5442         ent->eof = 1;
5443         return IMGTOOLERR_SUCCESS;
5444      }
5445      dataRecType = get_UINT16BE(catrec_data->dataType);
5446   } while (((dataRecType != hcrt_Folder) && (dataRecType != hcrt_File))
5447      || (get_UINT32BE(catrec_key->parID) != iter->u.hfs.catref.parID));
5448
5449   /* copy info */
5450   switch (get_UINT16BE(catrec_data->dataType))
5451   {
5452      case hcrt_Folder:
5453         ent->directory = 1;
5454         ent->filesize = 0;
5455         break;
5456
5457      case hcrt_File:
5458         ent->directory = 0;
5459         ent->filesize = get_UINT32BE(catrec_data->file.dataPhysicalSize)
5460            + get_UINT32BE(catrec_data->file.rsrcPhysicalSize);
5461         break;
5462   }
5463
5464   /* initialize file path buffer */
5465   cur_name_head = sizeof(ent->filename) / sizeof(ent->filename[0]);
5466   if (cur_name_head > 0)
5467   {
5468      cur_name_head--;
5469      ent->filename[cur_name_head] = '\0';
5470   }
5471
5472   /* insert folder/file name in buffer */
5473   mac_to_c_strncpy(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), catrec_key->cName);
5474//   concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, buf);
5475
5476#if 0
5477   /* extract parent directory ID */
5478   parID = get_UINT32BE(catrec_key->parID);
5479
5480   /* looping while (parID != 1) will display the volume name; looping while
5481   (parID != 2) won't */
5482   while (parID != /*1*/2)
5483   {
5484      /* search catalog for folder thread */
5485      err = hfs_cat_search(iter->l2_img, parID, mac_empty_str, &catrec_key, &catrec_data);
5486      if (err)
5487      {
5488         /* error */
5489         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, ":");
5490         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, "???");
5491
5492         memmove(ent->filename, ent->filename+cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - cur_name_head);
5493         ent->corrupt = 1;
5494         return err;
5495      }
5496
5497      dataRecType = get_UINT16BE(catrec_data->dataType);
5498
5499      if (dataRecType != hcrt_FolderThread)
5500      {
5501         /* error */
5502         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0])-1, ":");
5503         concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0])-1, "???");
5504
5505         memmove(ent->filename, ent->filename+cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0])-cur_name_head);
5506         ent->corrupt = 1;
5507         return IMGTOOLERR_CORRUPTIMAGE;
5508      }
5509
5510      /* got folder thread record: insert the folder name at the start of
5511      file path, then iterate */
5512      mac_to_c_strncpy(buf, sizeof(buf), catrec_data->thread.nodeName);
5513      concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, ":");
5514      concat_fname(ent->filename, &cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1, buf);
5515
5516      /* extract parent directory ID */
5517      parID = get_UINT32BE(catrec_data->thread.parID);
5518   }
5519   memmove(ent->filename, ent->filename+cur_name_head, sizeof(ent->filename) / sizeof(ent->filename[0]) -cur_name_head);
5520#endif
5521   return IMGTOOLERR_SUCCESS;
5522}
5523
5524/*
5525   Enumerate disk catalog next entry
5526*/
5527static imgtoolerr_t mac_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
5528{
5529   imgtoolerr_t err;
5530   mac_iterator *iter = (mac_iterator *) imgtool_directory_extrabytes(enumeration);
5531
5532   switch (iter->format)
5533   {
5534      case L2I_MFS:
5535         err = mfs_image_nextenum(iter, ent);
5536         break;
5537
5538      case L2I_HFS:
5539         err = hfs_image_nextenum(iter, ent);
5540         break;
5541
5542      default:
5543         assert(1);
5544         err = IMGTOOLERR_UNEXPECTED;
5545         break;
5546   }
5547   return err;
5548}
5549
5550/*
5551   Compute free space on disk image in bytes
5552*/
5553static imgtoolerr_t mac_image_freespace(imgtool_partition *partition, UINT64 *size)
5554{
5555   imgtool_image *image = imgtool_partition_image(partition);
5556   *size = ((UINT64) get_imgref(image)->freeABs) * 512;
5557   return IMGTOOLERR_SUCCESS;
5558}
5559
5560#ifdef UNUSED_FUNCTION
5561static imgtoolerr_t mac_get_comment(mac_l2_imgref *image, mac_str255 filename, const mac_dirent *cat_info, mac_str255 comment)
5562{
5563   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
5564   UINT16 commentID;
5565
5566   comment[0] = '\0';
5567
5568   /* get comment from Desktop file */
5569   switch (image->format)
5570   {
5571      case L2I_MFS:
5572         commentID = mfs_hashString(filename);
5573         err = get_comment(image, commentID, comment);
5574         break;
5575
5576      case L2I_HFS:
5577         /* This is the way to get Finder comments in system <= 7.  Attached
5578         comments use another method, and Finder 8 uses yet another one. */
5579         commentID = get_UINT16BE(cat_info->flXFinderInfo.comment);
5580         if (commentID)
5581            err = get_comment(image, commentID, comment);
5582         break;
5583   }
5584   return err;
5585}
5586#endif
5587
5588
5589/*
5590   Extract a file from a disk image.
5591*/
5592static imgtoolerr_t mac_image_readfile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *destf)
5593{
5594   imgtoolerr_t err;
5595   imgtool_image *img = imgtool_partition_image(partition);
5596   mac_l2_imgref *image = get_imgref(img);
5597   UINT32 parID;
5598   mac_str255 filename;
5599   mac_dirent cat_info;
5600   mac_fileref fileref;
5601   UINT8 buf[512];
5602   UINT32 i, run_len, data_len;
5603   mac_fork_t fork_num;
5604
5605   err = mac_identify_fork(fork, &fork_num);
5606   if (err)
5607      return err;
5608
5609   /* resolve path and fetch file info from directory/catalog */
5610   err = mac_lookup_path(image, fpath, &parID, filename, &cat_info, FALSE);
5611   if (err)
5612      return err;
5613   if (cat_info.dataRecType != hcrt_File)
5614      return IMGTOOLERR_FILENOTFOUND;
5615
5616   /* open file */
5617   err = mac_file_open(image, parID, filename, fork_num ? rsrc_fork : data_fork, &fileref);
5618   if (err)
5619      return err;
5620
5621   data_len = fork_num ? cat_info.rsrcLogicalSize : cat_info.dataLogicalSize;
5622
5623   /* extract DF */
5624   i = 0;
5625   while(i < data_len)
5626   {
5627      run_len = MIN(data_len - i, sizeof(buf));
5628
5629      err = mac_file_read(&fileref, run_len, buf);
5630      if (err)
5631         return err;
5632      if (stream_write(destf, buf, run_len) != run_len)
5633         return IMGTOOLERR_WRITEERROR;
5634      i += run_len;
5635   }
5636
5637   return IMGTOOLERR_SUCCESS;
5638}
5639
5640/*
5641   Add a file to a disk image.
5642*/
5643static imgtoolerr_t mac_image_writefile(imgtool_partition *partition, const char *fpath, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
5644{
5645   imgtool_image *img = imgtool_partition_image(partition);
5646   mac_l2_imgref *image = get_imgref(img);
5647   UINT32 parID;
5648   mac_str255 filename;
5649   mac_dirent cat_info;
5650   mac_fileref fileref;
5651   UINT32 fork_len;
5652   /*UINT16 commentID;
5653   mac_str255 comment;*/
5654   UINT8 buf[512];
5655   UINT32 i, run_len;
5656   imgtoolerr_t err;
5657   mac_fork_t fork_num;
5658
5659   (void) writeoptions;
5660
5661   if (image->format == L2I_HFS)
5662      return IMGTOOLERR_UNIMPLEMENTED;
5663
5664   err = mac_identify_fork(fork, &fork_num);
5665   if (err)
5666      return err;
5667
5668   /*if (header.version_old != 0)
5669      return IMGTOOLERR_UNIMPLEMENTED;*/
5670   /*mac_strcpy(filename, header.filename);*/
5671   memset(&cat_info, 0, sizeof(cat_info));
5672   set_UINT32BE(&cat_info.flFinderInfo.type, 0x3F3F3F3F);
5673   set_UINT32BE(&cat_info.flFinderInfo.creator, 0x3F3F3F3F);
5674   fork_len = stream_size(sourcef);
5675   /*comment[0] = get_UINT16BE(header.comment_len);*/   /* comment length */
5676   /* Next two fields are set to 0 with MFS volumes.  IIRC, 0 normally
5677   means system script: I don't think MFS stores the file name script code
5678   anywhere on disk, so it should be a reasonable approximation. */
5679
5680   /* create file */
5681   /* clear inited flag and file location in window */
5682   set_UINT16BE(&cat_info.flFinderInfo.flags, get_UINT16BE(cat_info.flFinderInfo.flags) & ~fif_hasBeenInited);
5683   set_UINT16BE(&cat_info.flFinderInfo.location.v, 0);
5684   set_UINT16BE(&cat_info.flFinderInfo.location.h, 0);
5685
5686   /* resolve path and create file */
5687   err = mac_lookup_path(image, fpath, &parID, filename, &cat_info, TRUE);
5688   if (err)
5689      return err;
5690
5691   /* open file fork */
5692   err = mac_file_open(image, parID, filename, (fork_num ? rsrc_fork : data_fork), &fileref);
5693   if (err)
5694      return err;
5695
5696   err = mac_file_seteof(&fileref, fork_len);
5697   if (err)
5698      return err;
5699
5700   /* extract fork */
5701   for (i=0; i<fork_len;)
5702   {
5703      run_len = fork_len - i;
5704      if (run_len > 512)
5705         run_len = 512;
5706      if (stream_read(sourcef, buf, run_len) != run_len)
5707         return IMGTOOLERR_READERROR;
5708      err = mac_file_write(&fileref, run_len, buf);
5709      if (err)
5710         return err;
5711      i += run_len;
5712   }
5713   return IMGTOOLERR_SUCCESS;
5714}
5715
5716
5717
5718static imgtoolerr_t mac_image_listforks(imgtool_partition *partition, const char *path, imgtool_forkent *ents, size_t len)
5719{
5720   imgtoolerr_t err;
5721   UINT32 parID;
5722   mac_str255 filename;
5723   mac_dirent cat_info;
5724   int fork_num = 0;
5725   imgtool_image *img = imgtool_partition_image(partition);
5726   mac_l2_imgref *image = get_imgref(img);
5727
5728   /* resolve path and fetch file info from directory/catalog */
5729   err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
5730   if (err)
5731      return err;
5732   if (cat_info.dataRecType != hcrt_File)
5733      return IMGTOOLERR_FILENOTFOUND;
5734
5735   /* specify data fork */
5736   ents[fork_num].type = FORK_DATA;
5737   ents[fork_num].forkname[0] = '\0';
5738   ents[fork_num].size = cat_info.dataLogicalSize;
5739   fork_num++;
5740
5741   if (cat_info.rsrcLogicalSize > 0)
5742   {
5743      /* specify the resource fork */
5744      ents[fork_num].type = FORK_RESOURCE;
5745      strcpy(ents[fork_num].forkname, "RESOURCE_FORK");
5746      ents[fork_num].size = cat_info.rsrcLogicalSize;
5747      fork_num++;
5748   }
5749
5750   ents[fork_num].type = FORK_END;
5751   return IMGTOOLERR_SUCCESS;
5752}
5753
5754
5755
5756static imgtoolerr_t mac_image_getattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, imgtool_attribute *values)
5757{
5758   imgtoolerr_t err;
5759   imgtool_image *img = imgtool_partition_image(partition);
5760   UINT32 parID;
5761   mac_str255 filename;
5762   mac_dirent cat_info;
5763   mac_l2_imgref *image = get_imgref(img);
5764   int i;
5765
5766   /* resolve path and fetch file info from directory/catalog */
5767   err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
5768   if (err)
5769      return err;
5770   if (cat_info.dataRecType != hcrt_File)
5771      return IMGTOOLERR_FILENOTFOUND;
5772
5773   for (i = 0; attrs[i]; i++)
5774   {
5775      switch(attrs[i])
5776      {
5777         case IMGTOOLATTR_INT_MAC_TYPE:
5778            values[i].i = get_UINT32BE(cat_info.flFinderInfo.type);
5779            break;
5780         case IMGTOOLATTR_INT_MAC_CREATOR:
5781            values[i].i = get_UINT32BE(cat_info.flFinderInfo.creator);
5782            break;
5783         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
5784            values[i].i = get_UINT16BE(cat_info.flFinderInfo.flags);
5785            break;
5786         case IMGTOOLATTR_INT_MAC_COORDX:
5787            values[i].i = get_UINT16BE(cat_info.flFinderInfo.location.h);
5788            break;
5789         case IMGTOOLATTR_INT_MAC_COORDY:
5790            values[i].i = get_UINT16BE(cat_info.flFinderInfo.location.v);
5791            break;
5792         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
5793            values[i].i = get_UINT16BE(cat_info.flFinderInfo.fldr);
5794            break;
5795         case IMGTOOLATTR_INT_MAC_ICONID:
5796            values[i].i = get_UINT16BE(cat_info.flXFinderInfo.iconID);
5797            break;
5798         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
5799            values[i].i = cat_info.flXFinderInfo.script;
5800            break;
5801         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
5802            values[i].i = cat_info.flXFinderInfo.XFlags;
5803            break;
5804         case IMGTOOLATTR_INT_MAC_COMMENTID:
5805            values[i].i = get_UINT16BE(cat_info.flXFinderInfo.comment);
5806            break;
5807         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
5808            values[i].i = get_UINT32BE(cat_info.flXFinderInfo.putAway);
5809            break;
5810
5811         case IMGTOOLATTR_TIME_CREATED:
5812            values[i].t = mac_crack_time(cat_info.createDate);
5813            break;
5814         case IMGTOOLATTR_TIME_LASTMODIFIED:
5815            values[i].t = mac_crack_time(cat_info.modifyDate);
5816            break;
5817      }
5818   }
5819   return IMGTOOLERR_SUCCESS;
5820}
5821
5822
5823
5824static imgtoolerr_t mac_image_setattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, const imgtool_attribute *values)
5825{
5826   imgtoolerr_t err;
5827   UINT32 parID;
5828   mac_str255 filename;
5829   mac_dirent cat_info;
5830   imgtool_image *img = imgtool_partition_image(partition);
5831   mac_l2_imgref *image = get_imgref(img);
5832   int i;
5833
5834   /* resolve path and fetch file info from directory/catalog */
5835   err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
5836   if (err)
5837      return err;
5838   if (cat_info.dataRecType != hcrt_File)
5839      return IMGTOOLERR_FILENOTFOUND;
5840
5841   for (i = 0; attrs[i]; i++)
5842   {
5843      switch(attrs[i])
5844      {
5845         case IMGTOOLATTR_INT_MAC_TYPE:
5846            set_UINT32BE(&cat_info.flFinderInfo.type, values[i].i);
5847            break;
5848         case IMGTOOLATTR_INT_MAC_CREATOR:
5849            set_UINT32BE(&cat_info.flFinderInfo.creator, values[i].i);
5850            break;
5851         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
5852            set_UINT16BE(&cat_info.flFinderInfo.flags, values[i].i);
5853            break;
5854         case IMGTOOLATTR_INT_MAC_COORDX:
5855            set_UINT16BE(&cat_info.flFinderInfo.location.h, values[i].i);
5856            break;
5857         case IMGTOOLATTR_INT_MAC_COORDY:
5858            set_UINT16BE(&cat_info.flFinderInfo.location.v, values[i].i);
5859            break;
5860         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
5861            set_UINT16BE(&cat_info.flFinderInfo.fldr, values[i].i);
5862            break;
5863         case IMGTOOLATTR_INT_MAC_ICONID:
5864            set_UINT16BE(&cat_info.flXFinderInfo.iconID, values[i].i);
5865            break;
5866         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
5867            cat_info.flXFinderInfo.script = values[i].i;
5868            break;
5869         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
5870            cat_info.flXFinderInfo.XFlags = values[i].i;
5871            break;
5872         case IMGTOOLATTR_INT_MAC_COMMENTID:
5873            set_UINT16BE(&cat_info.flXFinderInfo.comment, values[i].i);
5874            break;
5875         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
5876            set_UINT32BE(&cat_info.flXFinderInfo.putAway, values[i].i);
5877            break;
5878
5879         case IMGTOOLATTR_TIME_CREATED:
5880            cat_info.createDate = mac_setup_time(values[i].t);
5881            break;
5882         case IMGTOOLATTR_TIME_LASTMODIFIED:
5883            cat_info.modifyDate = mac_setup_time(values[i].t);
5884            break;
5885      }
5886   }
5887
5888   /* resolve path and fetch file info from directory/catalog */
5889   err = mac_lookup_path(image, path, &parID, filename, &cat_info, TRUE);
5890   if (err)
5891      return err;
5892
5893   return IMGTOOLERR_SUCCESS;
5894}
5895
5896
5897
5898/*************************************
5899 *
5900 *  Our very own resource manager
5901 *
5902 *************************************/
5903
5904static const void *mac_walk_resources(const void *resource_fork, size_t resource_fork_length,
5905   UINT32 resource_type,
5906   int (*discriminator)(const void *resource, UINT16 id, UINT32 length, void *param_),
5907   void *param, UINT16 *resource_id, UINT32 *resource_length)
5908{
5909   UINT32 resource_data_offset, resource_data_length;
5910   UINT32 resource_map_offset, resource_map_length;
5911   UINT32 resource_typelist_count, resource_typelist_offset;
5912   UINT32 resource_entry_offset, resource_entry_count;
5913   UINT32 i, this_resource_type;
5914   UINT32 this_resource_data, this_resource_length;
5915   UINT16 this_resource_id;
5916   const void *this_resource_ptr;
5917
5918   if (resource_fork_length < 16)
5919      return NULL;
5920
5921   /* read resource header; its ok if anything past this point fails */
5922   resource_data_offset = pick_integer_be(resource_fork,  0, 4);
5923   resource_map_offset  = pick_integer_be(resource_fork,  4, 4);
5924   resource_data_length = pick_integer_be(resource_fork,  8, 4);
5925   resource_map_length  = pick_integer_be(resource_fork, 12, 4);
5926   if ((resource_data_offset + resource_data_length) > resource_fork_length)
5927      return NULL;
5928   if ((resource_map_offset + resource_map_length) > resource_fork_length)
5929      return NULL;
5930   if (resource_map_length < 30)
5931      return NULL;
5932
5933   /* read resource map and locate the resource type list */
5934   resource_typelist_offset = pick_integer_be(resource_fork,
5935      resource_map_offset + 24, 2) + resource_map_offset;
5936   if ((resource_typelist_offset + 2) > resource_fork_length)
5937      return NULL;
5938   resource_typelist_count = pick_integer_be(resource_fork,
5939      resource_typelist_offset, 2) + 1;
5940   if ((resource_typelist_offset + resource_typelist_count * 16 + 2) > resource_fork_length)
5941      return NULL;
5942
5943   /* scan the resource type list and locate the entries for this type */
5944   resource_entry_count = 0;
5945   resource_entry_offset = 0;
5946   for (i = 0; i < resource_typelist_count; i++)
5947   {
5948      this_resource_type = pick_integer_be(resource_fork, resource_typelist_offset
5949         + (i * 8) + 2 + 0, 4);
5950      if (this_resource_type == resource_type)
5951      {
5952         resource_entry_count = pick_integer_be(resource_fork, resource_typelist_offset
5953            + (i * 8) + 2 + 4, 2) + 1;
5954         resource_entry_offset = pick_integer_be(resource_fork, resource_typelist_offset
5955            + (i * 8) + 2 + 6, 2) + resource_typelist_offset;
5956         break;
5957      }
5958   }
5959
5960   /* scan the resource entries, and find the correct resource */
5961   for (i = 0; i < resource_entry_count; i++)
5962   {
5963      this_resource_id = pick_integer_be(resource_fork, resource_entry_offset
5964         + (i * 12) + 0, 2);
5965      this_resource_data = pick_integer_be(resource_fork, resource_entry_offset
5966         + (i * 12) + 5, 3) + resource_data_offset;
5967      if ((this_resource_data + 4) > resource_fork_length)
5968         return NULL;
5969
5970      /* gauge the length */
5971      this_resource_length = pick_integer_be(resource_fork, this_resource_data, 4);
5972      this_resource_data += 4;
5973      if ((this_resource_data + this_resource_length) > resource_fork_length)
5974         return NULL;
5975
5976      this_resource_ptr = ((const UINT8 *) resource_fork) + this_resource_data;
5977      if (discriminator(this_resource_ptr, this_resource_id,
5978         this_resource_length, param))
5979      {
5980         if (resource_length)
5981            *resource_length = this_resource_length;
5982         if (resource_id)
5983            *resource_id = this_resource_id;
5984         return this_resource_ptr;
5985      }
5986   }
5987
5988   return NULL;
5989}
5990
5991
5992
5993static int get_resource_discriminator(const void *resource, UINT16 id, UINT32 length, void *param)
5994{
5995   const UINT16 *id_ptr = (const UINT16 *) param;
5996   return id == *id_ptr;
5997}
5998
5999
6000
6001static const void *mac_get_resource(const void *resource_fork, size_t resource_fork_length,
6002   UINT32 resource_type, UINT16 resource_id, UINT32 *resource_length)
6003{
6004   return mac_walk_resources(resource_fork, resource_fork_length,
6005      resource_type, get_resource_discriminator, &resource_id, NULL, resource_length);
6006}
6007
6008
6009
6010/*************************************
6011 *
6012 *  Custom icons
6013 *
6014 *************************************/
6015
6016static int bundle_discriminator(const void *resource, UINT16 id, UINT32 length, void *param)
6017{
6018   UINT32 this_creator_code = pick_integer_be(resource, 0, 4);
6019   UINT32 desired_creator_code = *((UINT32 *) param);
6020   return this_creator_code == desired_creator_code;
6021}
6022
6023
6024
6025static int get_pixel(const UINT8 *src, int width, int height, int bpp,
6026   int x, int y)
6027{
6028   UINT8 byte, mask;
6029   int bit_position;
6030
6031   byte = src[(y * width + x) * bpp / 8];
6032   bit_position = 8 - ((x % (8 / bpp)) + 1) * bpp;
6033   mask = (1 << bpp) - 1;
6034   return (byte >> bit_position) & mask;
6035}
6036
6037
6038
6039static int load_icon(UINT32 *dest, const void *resource_fork, UINT64 resource_fork_length,
6040   UINT32 resource_type, UINT16 resource_id, int width, int height, int bpp,
6041   const UINT32 *palette, int has_mask)
6042{
6043   int success = FALSE;
6044   int y, x, color, is_masked;
6045   UINT32 pixel;
6046   const UINT8 *src;
6047   UINT32 resource_length;
6048   UINT32 frame_length;
6049   UINT32 total_length;
6050
6051   frame_length = width * height * bpp / 8;
6052   total_length = frame_length * (has_mask ? 2 : 1);
6053
6054   /* attempt to fetch resource */
6055   src = mac_get_resource(resource_fork, resource_fork_length, resource_type,
6056      resource_id, &resource_length);
6057   if (src && (resource_length == total_length))
6058   {
6059      for (y = 0; y < height; y++)
6060      {
6061         for (x = 0; x < width; x ++)
6062         {
6063            /* first check mask bit */
6064            if (has_mask)
6065               is_masked = get_pixel(src + frame_length, width, height, bpp, x, y);
6066            else
6067               is_masked = dest[y * width + x] >= 0x80000000;
6068
6069            if (is_masked)
6070            {
6071               /* mask is ok; check the actual icon */
6072               color = get_pixel(src, width, height, bpp, x, y);
6073               pixel = palette[color] | 0xFF000000;
6074            }
6075            else
6076            {
6077               /* masked out; nothing */
6078               pixel = 0;
6079            }
6080
6081            dest[y * width + x] = pixel;
6082         }
6083      }
6084      success = TRUE;
6085   }
6086   return success;
6087}
6088
6089
6090
6091static imgtoolerr_t mac_image_geticoninfo(imgtool_partition *partition, const char *path, imgtool_iconinfo *iconinfo)
6092{
6093   static const UINT32 mac_palette_1bpp[2] = { 0xFFFFFF, 0x000000 };
6094
6095   static const UINT32 mac_palette_4bpp[16] =
6096   {
6097      0xFFFFFF, 0xFCF305, 0xFF6402, 0xDD0806, 0xF20884, 0x4600A5,
6098      0x0000D4, 0x02ABEA, 0x1FB714, 0x006411, 0x562C05, 0x90713A,
6099      0xC0C0C0, 0x808080, 0x404040, 0x000000
6100   };
6101
6102   static const UINT32 mac_palette_8bpp[256] =
6103   {
6104      0xFFFFFF, 0xFFFFCC, 0xFFFF99, 0xFFFF66, 0xFFFF33, 0xFFFF00,
6105      0xFFCCFF, 0xFFCCCC, 0xFFCC99, 0xFFCC66, 0xFFCC33, 0xFFCC00,
6106      0xFF99FF, 0xFF99CC, 0xFF9999, 0xFF9966, 0xFF9933, 0xFF9900,
6107      0xFF66FF, 0xFF66CC, 0xFF6699, 0xFF6666, 0xFF6633, 0xFF6600,
6108      0xFF33FF, 0xFF33CC, 0xFF3399, 0xFF3366, 0xFF3333, 0xFF3300,
6109      0xFF00FF, 0xFF00CC, 0xFF0099, 0xFF0066, 0xFF0033, 0xFF0000,
6110      0xCCFFFF, 0xCCFFCC, 0xCCFF99, 0xCCFF66, 0xCCFF33, 0xCCFF00,
6111      0xCCCCFF, 0xCCCCCC, 0xCCCC99, 0xCCCC66, 0xCCCC33, 0xCCCC00,
6112      0xCC99FF, 0xCC99CC, 0xCC9999, 0xCC9966, 0xCC9933, 0xCC9900,
6113      0xCC66FF, 0xCC66CC, 0xCC6699, 0xCC6666, 0xCC6633, 0xCC6600,
6114      0xCC33FF, 0xCC33CC, 0xCC3399, 0xCC3366, 0xCC3333, 0xCC3300,
6115      0xCC00FF, 0xCC00CC, 0xCC0099, 0xCC0066, 0xCC0033, 0xCC0000,
6116      0x99FFFF, 0x99FFCC, 0x99FF99, 0x99FF66, 0x99FF33, 0x99FF00,
6117      0x99CCFF, 0x99CCCC, 0x99CC99, 0x99CC66, 0x99CC33, 0x99CC00,
6118      0x9999FF, 0x9999CC, 0x999999, 0x999966, 0x999933, 0x999900,
6119      0x9966FF, 0x9966CC, 0x996699, 0x996666, 0x996633, 0x996600,
6120      0x9933FF, 0x9933CC, 0x993399, 0x993366, 0x993333, 0x993300,
6121      0x9900FF, 0x9900CC, 0x990099, 0x990066, 0x990033, 0x990000,
6122      0x66FFFF, 0x66FFCC, 0x66FF99, 0x66FF66, 0x66FF33, 0x66FF00,
6123      0x66CCFF, 0x66CCCC, 0x66CC99, 0x66CC66, 0x66CC33, 0x66CC00,
6124      0x6699FF, 0x6699CC, 0x669999, 0x669966, 0x669933, 0x669900,
6125      0x6666FF, 0x6666CC, 0x666699, 0x666666, 0x666633, 0x666600,
6126      0x6633FF, 0x6633CC, 0x663399, 0x663366, 0x663333, 0x663300,
6127      0x6600FF, 0x6600CC, 0x660099, 0x660066, 0x660033, 0x660000,
6128      0x33FFFF, 0x33FFCC, 0x33FF99, 0x33FF66, 0x33FF33, 0x33FF00,
6129      0x33CCFF, 0x33CCCC, 0x33CC99, 0x33CC66, 0x33CC33, 0x33CC00,
6130      0x3399FF, 0x3399CC, 0x339999, 0x339966, 0x339933, 0x339900,
6131      0x3366FF, 0x3366CC, 0x336699, 0x336666, 0x336633, 0x336600,
6132      0x3333FF, 0x3333CC, 0x333399, 0x333366, 0x333333, 0x333300,
6133      0x3300FF, 0x3300CC, 0x330099, 0x330066, 0x330033, 0x330000,
6134      0x00FFFF, 0x00FFCC, 0x00FF99, 0x00FF66, 0x00FF33, 0x00FF00,
6135      0x00CCFF, 0x00CCCC, 0x00CC99, 0x00CC66, 0x00CC33, 0x00CC00,
6136      0x0099FF, 0x0099CC, 0x009999, 0x009966, 0x009933, 0x009900,
6137      0x0066FF, 0x0066CC, 0x006699, 0x006666, 0x006633, 0x006600,
6138      0x0033FF, 0x0033CC, 0x003399, 0x003366, 0x003333, 0x003300,
6139      0x0000FF, 0x0000CC, 0x000099, 0x000066, 0x000033, 0xEE0000,
6140      0xDD0000, 0xBB0000, 0xAA0000, 0x880000, 0x770000, 0x550000,
6141      0x440000, 0x220000, 0x110000, 0x00EE00, 0x00DD00, 0x00BB00,
6142      0x00AA00, 0x008800, 0x007700, 0x005500, 0x004400, 0x002200,
6143      0x001100, 0x0000EE, 0x0000DD, 0x0000BB, 0x0000AA, 0x000088,
6144      0x000077, 0x000055, 0x000044, 0x000022, 0x000011, 0xEEEEEE,
6145      0xDDDDDD, 0xBBBBBB, 0xAAAAAA, 0x888888, 0x777777, 0x555555,
6146      0x444444, 0x222222, 0x111111, 0x000000
6147   };
6148
6149   static const UINT32 attrs[4] =
6150   {
6151      IMGTOOLATTR_INT_MAC_TYPE,
6152      IMGTOOLATTR_INT_MAC_CREATOR,
6153      IMGTOOLATTR_INT_MAC_FINDERFLAGS
6154   };
6155
6156   imgtoolerr_t err;
6157   imgtool_attribute attr_values[3];
6158   UINT32 type_code, creator_code, finder_flags;
6159   imgtool_stream *stream = NULL;
6160   const void *resource_fork;
6161   UINT64 resource_fork_length;
6162   const void *bundle;
6163   UINT32 bundle_length, pos, fref_pos, icn_pos, i;
6164   UINT16 local_id = 0, resource_id;
6165   UINT32 fref_bundleentry_length, icn_bundleentry_length;
6166   const void *fref;
6167   UINT32 resource_length;
6168
6169   assert((sizeof(attrs) / sizeof(attrs[0]) - 1)
6170      == (sizeof(attr_values) / sizeof(attr_values[0])));
6171
6172   /* first retrieve type and creator code */
6173   err = mac_image_getattrs(partition, path, attrs, attr_values);
6174   if (err)
6175      goto done;
6176   type_code = (UINT32) attr_values[0].i;
6177   creator_code = (UINT32) attr_values[1].i;
6178   finder_flags = (UINT32) attr_values[2].i;
6179
6180   /* check the bundle bit; if clear (and the type is not 'APPL'), use the
6181    * desktop file */
6182   if (!(finder_flags & 0x2000) && (type_code != /* APPL */ 0x4150504C))
6183      path = "Desktop\0";
6184
6185   stream = stream_open_mem(NULL, 0);
6186   if (!stream)
6187   {
6188      err = IMGTOOLERR_SUCCESS;
6189      goto done;
6190   }
6191
6192   /* read in the resource fork */
6193   err = mac_image_readfile(partition, path, "RESOURCE_FORK", stream);
6194   if (err)
6195      goto done;
6196   resource_fork = stream_getptr(stream);
6197   resource_fork_length = stream_size(stream);
6198
6199   /* attempt to look up the bundle */
6200   bundle = mac_walk_resources(resource_fork, resource_fork_length, /* BNDL */ 0x424E444C,
6201      bundle_discriminator, &creator_code, NULL, &bundle_length);
6202   if (!bundle)
6203      goto done;
6204
6205   /* find the FREF and the icon family */
6206   pos = 8;
6207   fref_pos = icn_pos = 0;
6208   fref_bundleentry_length = icn_bundleentry_length = 0;
6209   while((pos + 10) <= bundle_length)
6210   {
6211      UINT32 this_bundleentry_type = pick_integer_be(bundle, pos + 0, 4);
6212      UINT32 this_bundleentry_length = pick_integer_be(bundle, pos + 4, 2) + 1;
6213
6214      if (this_bundleentry_type == /* FREF */ 0x46524546)
6215      {
6216         fref_pos = pos;
6217         fref_bundleentry_length = this_bundleentry_length;
6218      }
6219      if (this_bundleentry_type == /* ICN# */ 0x49434E23)
6220      {
6221         icn_pos = pos;
6222         icn_bundleentry_length = this_bundleentry_length;
6223      }
6224      pos += 6 + this_bundleentry_length * 4;
6225   }
6226   if (!fref_pos || !icn_pos)
6227      goto done;
6228
6229   /* look up the FREF */
6230   for (i = 0; i < fref_bundleentry_length; i++)
6231   {
6232      local_id = pick_integer_be(bundle, fref_pos + (i * 4) + 6, 2);
6233      resource_id = pick_integer_be(bundle, fref_pos + (i * 4) + 8, 2);
6234
6235      fref = mac_get_resource(resource_fork, resource_fork_length,
6236         /* FREF */ 0x46524546, resource_id, &resource_length);
6237      if (fref && (resource_length >= 7))
6238      {
6239         if (pick_integer_be(fref, 0, 4) == type_code)
6240            break;
6241      }
6242   }
6243   if (i >= fref_bundleentry_length)
6244      goto done;
6245
6246   /* now look up the icon family */
6247   resource_id = 0;
6248   for (i = 0; i < icn_bundleentry_length; i++)
6249   {
6250      if (pick_integer_be(bundle, icn_pos + (i * 4) + 6, 2) == local_id)
6251      {
6252         resource_id = pick_integer_be(bundle, icn_pos + (i * 4) + 8, 2);
6253         break;
6254      }
6255   }
6256   if (i >= icn_bundleentry_length)
6257      goto done;
6258
6259   /* fetch 32x32 icons (ICN#, icl4, icl8) */
6260   if (load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6261      /* ICN# */ 0x49434E23, resource_id, 32, 32, 1, mac_palette_1bpp, TRUE))
6262   {
6263      iconinfo->icon32x32_specified = 1;
6264
6265      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6266         /* icl4 */ 0x69636C34, resource_id, 32, 32, 4, mac_palette_4bpp, FALSE);
6267      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6268         /* icl8 */ 0x69636C38, resource_id, 32, 32, 8, mac_palette_8bpp, FALSE);
6269   }
6270
6271   /* fetch 16x16 icons (ics#, ics4, ics8) */
6272   if (load_icon((UINT32 *) iconinfo->icon16x16, resource_fork, resource_fork_length,
6273      /* ics# */ 0x69637323, resource_id, 16, 16, 1, mac_palette_1bpp, TRUE))
6274   {
6275      iconinfo->icon16x16_specified = 1;
6276
6277      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6278         /* ics4 */ 0x69637334, resource_id, 32, 32, 4, mac_palette_4bpp, FALSE);
6279      load_icon((UINT32 *) iconinfo->icon32x32, resource_fork, resource_fork_length,
6280         /* ics8 */ 0x69637338, resource_id, 32, 32, 8, mac_palette_8bpp, FALSE);
6281   }
6282
6283done:
6284   if (stream)
6285      stream_close(stream);
6286   return err;
6287}
6288
6289
6290
6291/*************************************
6292 *
6293 *  File transfer suggestions
6294 *
6295 *************************************/
6296
6297static imgtoolerr_t mac_image_suggesttransfer(imgtool_partition *partition, const char *path, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
6298{
6299   imgtoolerr_t err;
6300   UINT32 parID;
6301   mac_str255 filename;
6302   mac_dirent cat_info;
6303   imgtool_image *img = imgtool_partition_image(partition);
6304   mac_l2_imgref *image = get_imgref(img);
6305   mac_filecategory_t file_category = MAC_FILECATEGORY_DATA;
6306
6307   if (path)
6308   {
6309      /* resolve path and fetch file info from directory/catalog */
6310      err = mac_lookup_path(image, path, &parID, filename, &cat_info, FALSE);
6311      if (err)
6312         return err;
6313      if (cat_info.dataRecType != hcrt_File)
6314         return IMGTOOLERR_FILENOTFOUND;
6315
6316      file_category = (cat_info.rsrcLogicalSize > 0) ? MAC_FILECATEGORY_FORKED : MAC_FILECATEGORY_DATA;
6317   }
6318
6319   mac_suggest_transfer(file_category, suggestions, suggestions_length);
6320   return IMGTOOLERR_SUCCESS;
6321}
6322
6323
6324
6325/*************************************
6326 *
6327 *  Module population
6328 *
6329 *************************************/
6330
6331static void generic_mac_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
6332{
6333   switch(state)
6334   {
6335      /* --- the following bits of info are returned as 64-bit signed integers --- */
6336      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
6337      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(struct mac_l2_imgref); break;
6338      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(struct mac_iterator); break;
6339      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = ':'; break;
6340
6341      /* --- the following bits of info are returned as NULL-terminated strings --- */
6342      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
6343      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
6344
6345      /* --- the following bits of info are returned as pointers to data or functions --- */
6346      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
6347      case IMGTOOLINFO_PTR_CLOSE:                     /* info->close = mac_image_exit */; break;
6348      case IMGTOOLINFO_PTR_INFO:                     info->info = mac_image_info; break;
6349      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = mac_image_beginenum; break;
6350      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = mac_image_nextenum; break;
6351      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = mac_image_freespace; break;
6352      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = mac_image_readfile; break;
6353      case IMGTOOLINFO_PTR_LIST_FORKS:               info->list_forks = mac_image_listforks; break;
6354      case IMGTOOLINFO_PTR_GET_ATTRS:                  info->get_attrs = mac_image_getattrs; break;
6355      case IMGTOOLINFO_PTR_SET_ATTRS:                  info->set_attrs = mac_image_setattrs; break;
6356      case IMGTOOLINFO_PTR_GET_ICON_INFO:               info->get_iconinfo = mac_image_geticoninfo; break;
6357      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = mac_image_suggesttransfer; break;
6358      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_apple35_mac; break;
6359   }
6360}
6361
6362
6363
6364void mac_mfs_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
6365{
6366   switch(state)
6367   {
6368      /* --- the following bits of info are returned as NULL-terminated strings --- */
6369      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "mac_mfs"); break;
6370      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "Mac MFS Floppy"); break;
6371
6372      /* --- the following bits of info are returned as pointers to data or functions --- */
6373      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = mfs_image_create; break;
6374      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = mfs_image_open; break;
6375      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = mac_image_writefile; break;
6376
6377      default: generic_mac_get_info(imgclass, state, info); break;
6378   }
6379}
6380
6381
6382
6383void mac_hfs_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
6384{
6385   switch(state)
6386   {
6387      /* --- the following bits of info are returned as NULL-terminated strings --- */
6388      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "mac_hfs"); break;
6389      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "Mac HFS Floppy"); break;
6390
6391      /* --- the following bits of info are returned as pointers to data or functions --- */
6392      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = hfs_image_open; break;
6393
6394      default: generic_mac_get_info(imgclass, state, info); break;
6395   }
6396}
src/mess/tools/imgtool/modules/pc_hard.c
r0r1340
1/****************************************************************************
2
3   pc_hard.c
4
5   PC hard drives
6
7*****************************************************************************
8
9  Master boot record format:
10
11  Offset  Length  Description
12  ------  ------  -----------
13       0     446  Boot machine code
14     446      16  Partion #1 info
15     462      16  Partion #2 info
16     478      16  Partion #3 info
17     494      16  Partion #4 info
18    510       2  Magic bytes (0x55 0xAA)
19
20
21  Partition info format:
22
23  Offset  Length  Description
24  ------  ------  -----------
25       0       1  Bootable (0x80=bootable 0x00=not bootable)
26      1       1  Starting head
27      2       1  Starting sector (bits 5-0) and high bits of starting track (bits 6-5)
28      3       1  Low bits of starting track
29      4       1  Partition type:
30                   0x00      Unused
31                  0x?1      FAT12   (0-15 MB)
32                  0x?2      XENIX
33                  0x?4      FAT16   (16-32 MB)
34                  0x?6      FAT16`   (32 MB-2 GB)
35                  0x?7      HPFS or NTFS
36                  0x?A      Boot Manager
37                  0x?B      FAT32   (512 MB-2 TB)
38                  0x?C      FAT32   (512 MB-2 TB LBA)
39                  0x1?      OS/2 Boot manager/Win95 hidden
40                  0xC?      DR-DOS secured partition
41                  0xD?      Multiuser DOS secured partition
42                  0xE?      SpeedStor extended partition
43      5       1  Ending head
44      6       1  Ending sector (bits 5-0) and high bits of ending track (bits 6-5)
45      7       1  Low bits of ending track
46      8       4  Sector index of beginning of partition
47     12       4  Total sectors in partition
48
49****************************************************************************/
50
51#include "imgtool.h"
52#include "imghd.h"
53
54#define FAT_SECLEN   512
55
56OPTION_GUIDE_START( pc_chd_create_optionguide )
57   OPTION_INT('T', "cylinders",   "Cylinders" )
58   OPTION_INT('H', "heads",      "Heads" )
59   OPTION_INT('S', "sectors",      "Sectors" )
60OPTION_GUIDE_END
61
62static const char pc_chd_create_optionspec[] = "H1-[16]S1-[32]-63T10/20/30/40/50/60/70/80/90/[100]/110/120/130/140/150/160/170/180/190/200";
63
64static const char fat8_string[8]  = { 'F', 'A', 'T', ' ', ' ', ' ', ' ', ' ' };
65static const char fat12_string[8] = { 'F', 'A', 'T', '1', '2', ' ', ' ', ' ' };
66static const char fat16_string[8] = { 'F', 'A', 'T', '1', '6', ' ', ' ', ' ' };
67static const char fat32_string[8] = { 'F', 'A', 'T', '3', '2', ' ', ' ', ' ' };
68
69/* imports from fat.c */
70extern void fat_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info);
71
72
73typedef struct _pc_chd_image_info pc_chd_image_info;
74struct _pc_chd_image_info
75{
76   struct mess_hard_disk_file hard_disk;
77
78   struct
79   {
80      unsigned int corrupt : 1;
81      UINT8 partition_type;
82      UINT32 fat_bits;
83      UINT32 starting_track;
84      UINT32 starting_head;
85      UINT32 starting_sector;
86      UINT32 ending_track;
87      UINT32 ending_head;
88      UINT32 ending_sector;
89      UINT32 sector_index;
90      UINT32 total_sectors;
91   } partitions[4];
92};
93
94
95
96static pc_chd_image_info *pc_chd_get_image_info(imgtool_image *image)
97{
98   return (pc_chd_image_info *) imgtool_image_extra_bytes(image);
99}
100
101
102
103static void pc_chd_locate_block(imgtool_image *image, UINT64 block, UINT32 *cylinder, UINT32 *head, UINT32 *sector)
104{
105   pc_chd_image_info *info;
106   const hard_disk_info *hd_info;
107
108   info = pc_chd_get_image_info(image);
109   hd_info = imghd_get_header(&info->hard_disk);
110
111   *sector = block % hd_info->sectors;
112   *head = (block / hd_info->sectors) % hd_info->heads;
113   *cylinder = block / hd_info->sectors / hd_info->heads;
114}
115
116
117
118static imgtoolerr_t pc_chd_partition_create(imgtool_image *image, int partition_index, UINT64 first_block, UINT64 block_count)
119{
120   imgtoolerr_t err;
121   UINT8 header_block[FAT_SECLEN];
122   UINT8 partition_block[FAT_SECLEN];
123   UINT8 partition_type;
124   UINT8 *fat_type;
125   UINT8 *partition_entry;
126   UINT32 first_cylinder, first_head, first_sector;
127   UINT32 last_cylinder, last_head, last_sector;
128   imgtool_class imgclass = { fat_get_info };
129   imgtoolerr_t (*fat_partition_create)(imgtool_image *image, UINT64 first_block, UINT64 block_count);
130
131   /* sanity checks */
132   assert((partition_index >= 0) && (partition_index <= 3));
133
134   /* compute geometry */
135   pc_chd_locate_block(image, first_block, &first_cylinder, &first_head, &first_sector);
136   pc_chd_locate_block(image, first_block + block_count - 1, &last_cylinder, &last_head, &last_sector);
137
138   /* load fat_partition_create */
139   fat_partition_create = (imgtoolerr_t (*)(imgtool_image *, UINT64, UINT64))
140      imgtool_get_info_fct(&imgclass, IMGTOOLINFO_PTR_CREATE_PARTITION);
141
142   /* first create the actual partition */
143   err = fat_partition_create(image, first_block, block_count);
144   if (err)
145      goto done;
146
147   /* read the first block of the partition, to determine the type of FAT */
148   err = imgtool_image_read_block(image, first_block, partition_block);
149   if (err)
150      goto done;
151   fat_type = &partition_block[54];
152   if (!memcmp(fat_type, fat8_string, sizeof(fat8_string)))
153      partition_type = 0x01;
154   else if (!memcmp(fat_type, fat12_string, sizeof(fat12_string)))
155      partition_type = 0x01;
156   else if ((!memcmp(fat_type, fat16_string, sizeof(fat16_string))) && (block_count < 32*1024*1024/FAT_SECLEN))
157      partition_type = 0x04;
158   else if ((!memcmp(fat_type, fat16_string, sizeof(fat16_string))) && (block_count >= 32*1024*1024/FAT_SECLEN))
159      partition_type = 0x06;
160   else
161      partition_type = 0x0B;
162
163   /* read the partition header */
164   err = imgtool_image_read_block(image, 0, header_block);
165   if (err)
166      goto done;
167
168   /* fill out the partition entry */
169   partition_entry = &header_block[446 + (partition_index * 16)];
170   place_integer_le(partition_entry,  0, 1, 0x80);
171   place_integer_le(partition_entry,  1, 1, first_head);
172   place_integer_le(partition_entry,  2, 1, ((first_sector & 0x3F) | (first_cylinder >> 8 << 2)));
173   place_integer_le(partition_entry,  3, 1, first_cylinder);
174   place_integer_le(partition_entry,  4, 1, partition_type);
175   place_integer_le(partition_entry,  5, 1, last_head);
176   place_integer_le(partition_entry,  6, 1, ((last_sector & 0x3F) | (last_cylinder >> 8 << 2)));
177   place_integer_le(partition_entry,  7, 1, last_cylinder);
178   place_integer_le(partition_entry,  8, 4, first_block);
179   place_integer_le(partition_entry, 12, 4, block_count);
180
181   /* write the partition header */
182   err = imgtool_image_write_block(image, 0, header_block);
183   if (err)
184      goto done;
185
186done:
187   return err;
188}
189
190
191
192static imgtoolerr_t pc_chd_read_partition_header(imgtool_image *image)
193{
194   imgtoolerr_t err;
195   int i;
196   const UINT8 *partition_info;
197   pc_chd_image_info *info;
198   UINT8 buffer[FAT_SECLEN];
199
200   info = pc_chd_get_image_info(image);
201
202   /* read the initial block */
203   err = imgtool_image_read_block(image, 0, buffer);
204   if (err)
205      return err;
206
207   /* magic bytes present? */
208   if ((buffer[510] != 0x55) || (buffer[511] != 0xAA))
209      return IMGTOOLERR_CORRUPTIMAGE;
210
211   for (i = 0; i < sizeof(info->partitions) / sizeof(info->partitions[0]); i++)
212   {
213      partition_info = &buffer[446 + i * 16];
214
215      info->partitions[i].partition_type   = partition_info[4];
216      info->partitions[i].starting_head   = partition_info[1];
217      info->partitions[i].starting_track   = ((partition_info[2] << 2) & 0xFF00) | partition_info[3];
218      info->partitions[i].starting_sector   = partition_info[2] & 0x3F;
219      info->partitions[i].ending_head      = partition_info[5];
220      info->partitions[i].ending_track   = ((partition_info[6] << 2) & 0xFF00) | partition_info[7];
221      info->partitions[i].ending_sector   = partition_info[6] & 0x3F;
222
223      info->partitions[i].sector_index   = pick_integer_le(partition_info,  8, 4);
224      info->partitions[i].total_sectors   = pick_integer_le(partition_info, 12, 4);
225
226      if (info->partitions[i].starting_track > info->partitions[i].ending_track)
227         return IMGTOOLERR_CORRUPTIMAGE;
228   }
229   return IMGTOOLERR_SUCCESS;
230}
231
232
233
234static imgtoolerr_t pc_chd_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *opts)
235{
236   imgtoolerr_t err;
237   UINT32 cylinders, heads, sectors;
238   pc_chd_image_info *info;
239   UINT8 header_block[FAT_SECLEN];
240
241   cylinders = option_resolution_lookup_int(opts, 'T');
242   heads = option_resolution_lookup_int(opts, 'H');
243   sectors = option_resolution_lookup_int(opts, 'S');
244
245   info = pc_chd_get_image_info(image);
246
247   /* create the hard disk image */
248   err = imghd_create(f, 0, cylinders, heads, sectors, FAT_SECLEN);
249   if (err)
250      goto done;
251
252   err = imghd_open(f, &info->hard_disk);
253   if (err)
254      goto done;
255
256   /* set up partition header block */
257   memset(header_block, 0, sizeof(header_block));
258   header_block[510] = 0x55;
259   header_block[511] = 0xAA;
260   err = imgtool_image_write_block(image, 0, header_block);
261   if (err)
262      goto done;
263
264   err = pc_chd_partition_create(image, 0, 1, cylinders * heads * sectors - 1);
265   if (err)
266      goto done;
267
268   err = pc_chd_read_partition_header(image);
269   if (err)
270      goto done;
271
272done:
273   if (err)
274      imghd_close(&info->hard_disk);
275   return err;
276}
277
278
279
280static imgtoolerr_t pc_chd_image_open(imgtool_image *image, imgtool_stream *stream)
281{
282   imgtoolerr_t err;
283   pc_chd_image_info *info;
284
285   info = pc_chd_get_image_info(image);
286
287   /* open the hard drive */
288   err = imghd_open(stream, &info->hard_disk);
289   if (err)
290      return err;
291
292   err = pc_chd_read_partition_header(image);
293   if (err)
294      return err;
295
296   return IMGTOOLERR_SUCCESS;
297}
298
299
300
301static void pc_chd_image_close(imgtool_image *image)
302{
303   pc_chd_image_info *info;
304   info = pc_chd_get_image_info(image);
305   imghd_close(&info->hard_disk);
306}
307
308
309
310static imgtoolerr_t pc_chd_image_get_geometry(imgtool_image *image, UINT32 *tracks, UINT32 *heads, UINT32 *sectors)
311{
312   pc_chd_image_info *info;
313   const hard_disk_info *hd_info;
314
315   info = pc_chd_get_image_info(image);
316   hd_info = imghd_get_header(&info->hard_disk);
317
318   *tracks = hd_info->cylinders;
319   *heads = hd_info->heads;
320   *sectors = hd_info->sectors;
321   return IMGTOOLERR_SUCCESS;
322}
323
324
325
326static imgtoolerr_t   pc_chd_image_getsectorsize(imgtool_image *image, UINT32 track, UINT32 head, UINT32 sector, UINT32 *sector_size)
327{
328   pc_chd_image_info *info;
329   info = pc_chd_get_image_info(image);
330   *sector_size = imghd_get_header(&info->hard_disk)->sectorbytes;
331   return IMGTOOLERR_SUCCESS;
332}
333
334
335
336static UINT32 pc_chd_calc_lbasector(pc_chd_image_info *info, UINT32 track, UINT32 head, UINT32 sector)
337{
338   UINT32 lbasector;
339   const hard_disk_info *hd_info;
340
341   hd_info = imghd_get_header(&info->hard_disk);
342   lbasector = track;
343   lbasector *= hd_info->heads;
344   lbasector += head;
345   lbasector *= hd_info->sectors;
346   lbasector += sector;
347   return lbasector;
348}
349
350
351
352static imgtoolerr_t   pc_chd_image_readsector(imgtool_image *image, UINT32 track, UINT32 head, UINT32 sector, void *buffer, size_t len)
353{
354   pc_chd_image_info *info;
355   info = pc_chd_get_image_info(image);
356   return imghd_read(&info->hard_disk,
357      pc_chd_calc_lbasector(info, track, head, sector),
358      buffer);
359}
360
361
362
363static imgtoolerr_t   pc_chd_image_writesector(imgtool_image *image, UINT32 track, UINT32 head, UINT32 sector, const void *buffer, size_t len)
364{
365   pc_chd_image_info *info;
366   info = pc_chd_get_image_info(image);
367   return imghd_write(&info->hard_disk,
368      pc_chd_calc_lbasector(info, track, head, sector),
369      buffer);
370}
371
372
373
374static imgtoolerr_t pc_chd_image_readblock(imgtool_image *image, void *buffer, UINT64 block)
375{
376   pc_chd_image_info *info;
377   info = pc_chd_get_image_info(image);
378   return imghd_read(&info->hard_disk, block, buffer);
379}
380
381
382
383static imgtoolerr_t pc_chd_image_writeblock(imgtool_image *image, const void *buffer, UINT64 block)
384{
385   pc_chd_image_info *info;
386   info = pc_chd_get_image_info(image);
387   return imghd_write(&info->hard_disk, block, buffer);
388}
389
390
391
392static imgtoolerr_t pc_chd_list_partitions(imgtool_image *image, imgtool_partition_info *partitions, size_t len)
393{
394   pc_chd_image_info *info;
395   size_t i;
396
397   info = pc_chd_get_image_info(image);
398
399   for (i = 0; i < MIN(4, len); i++)
400   {
401      partitions[i].base_block   = info->partitions[i].sector_index;
402      partitions[i].block_count   = info->partitions[i].total_sectors;
403
404      switch(info->partitions[i].partition_type)
405      {
406         case 0x00:   /* Empty Partition */
407            partitions[i].get_info = NULL;
408            break;
409
410         case 0x01:   /* FAT12 */
411         case 0x04:   /* FAT16 (-32 MB) */
412         case 0x06:   /* FAT16 (32+ MB) */
413         case 0x0B:   /* FAT32 */
414         case 0x0C:   /* FAT32 (LBA Mapped) */
415         case 0x0E:   /* FAT16 (LBA Mapped) */
416         case 0x11:   /* OS/2 FAT12 */
417         case 0x14:   /* OS/2 FAT16 (-32 MB) */
418         case 0x16:   /* OS/2 FAT16 (32+ MB) */
419         case 0x1B:   /* Hidden Win95 FAT32 */
420         case 0x1C:   /* Hidden Win95 FAT32 (LBA Mapped) */
421         case 0x1D:   /* Hidden Win95 FAT16 (LBA Mapped) */
422         case 0xC1:   /* DR-DOS FAT12 */
423         case 0xC4:   /* DR-DOS FAT16 (-32 MB) */
424         case 0xC6:   /* DR-DOS FAT16 (32+ MB) */
425         case 0xD1:   /* Old Multiuser DOS FAT12 */
426         case 0xD4:   /* Old Multiuser DOS FAT16 (-32 MB) */
427         case 0xD6:   /* Old Multiuser DOS FAT16 (32+ MB) */
428            partitions[i].get_info = fat_get_info;
429            break;
430
431         default:
432            partitions[i].get_info = unknown_partition_get_info;
433            break;
434      }
435   }
436   return IMGTOOLERR_SUCCESS;
437}
438
439
440
441void pc_chd_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
442{
443   switch(state)
444   {
445      /* --- the following bits of info are returned as 64-bit signed integers --- */
446      case IMGTOOLINFO_INT_BLOCK_SIZE:               info->i = FAT_SECLEN; break;
447      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(pc_chd_image_info); break;
448      case IMGTOOLINFO_INT_TRACKS_ARE_CALLED_CYLINDERS:   info->i = 1; break;
449
450      /* --- the following bits of info are returned as NULL-terminated strings --- */
451      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "pc_chd"); break;
452      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "PC CHD disk image"); break;
453      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "chd"); break;
454      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:         strcpy(info->s = imgtool_temp_str(), pc_chd_create_optionspec); break;
455
456      /* --- the following bits of info are returned as pointers to data or functions --- */
457      case IMGTOOLINFO_PTR_CREATE:                  info->create = pc_chd_image_create; break;
458      case IMGTOOLINFO_PTR_OPEN:                     info->open = pc_chd_image_open; break;
459      case IMGTOOLINFO_PTR_CLOSE:                     info->close = pc_chd_image_close; break;
460      case IMGTOOLINFO_PTR_READ_SECTOR:               info->read_sector = pc_chd_image_readsector; break;
461      case IMGTOOLINFO_PTR_WRITE_SECTOR:               info->write_sector = pc_chd_image_writesector; break;
462      case IMGTOOLINFO_PTR_READ_BLOCK:               info->read_block = pc_chd_image_readblock; break;
463      case IMGTOOLINFO_PTR_WRITE_BLOCK:               info->write_block = pc_chd_image_writeblock; break;
464      case IMGTOOLINFO_PTR_GET_SECTOR_SIZE:            info->get_sector_size = pc_chd_image_getsectorsize; break;
465      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:         info->createimage_optguide = pc_chd_create_optionguide; break;
466      case IMGTOOLINFO_PTR_GET_GEOMETRY:               info->get_geometry = pc_chd_image_get_geometry; break;
467      case IMGTOOLINFO_PTR_LIST_PARTITIONS:            info->list_partitions = pc_chd_list_partitions; break;
468   }
469}
src/mess/tools/imgtool/modules/vmsx_tap.c
r0r1340
1/*
2    vMSX tap format
3
4    Virtual MSX 1.x (being replaced by the MSX driver in mess) had
5    it's on format for cassette recordings. The format is similar
6    to .cas files; however several recordings could be stored in
7    one file.
8
9    Virtual MSX was never really popular; I haven't seen any of these
10    files on the internet. However for completeness sake I've added
11    this converter. It's read only; the MSX driver cannot read
12    these files, but can read the .cas files (like most other MSX
13    emulators). Further use and specially distribution of the .tap files
14    is discouraged as Virtual MSX is obsolete (along with its private
15    file formats).
16
17    These files used the M$ mmio functions (similar to .aiff files). There
18    is an INFO block which lists all files in the archive. The TAPE block
19    contains the actual data.
20
21   Original code in Virtual MSX:
22
23      ftp://ftp.komkon.org/pub/EMUL8/MSX/Emulators/VMSX1SRC.zip
24   
25   It's in the file TAPE.C.
26
27   RIFF format specs:
28
29      http://www.saettler.com/RIFFMCI/riffmci.html
30
31
32    This module converts the files to .cas files. Implemented are:
33
34    dir - list all the files in the archive as "%title%-%type%.cas"
35    getall - writes all the files to disk
36    get - gets one file. If "getall" fails, due to characters in the
37          filename your FS/OS doesn't support, use:
38
39   imgtool get vmsx_tap monmsx.tap monmsx-binary.cas monmsx.cas
40
41    for example.
42
43   Sean Young
44*/
45
46#include "osdepend.h"
47#include "imgtoolx.h"
48#include "utils.h"
49
50typedef struct
51    {
52    char        title[32];
53    char        type[10];
54    char       chunk[4];
55    } TAP_ENTRY;
56
57typedef struct
58   {
59   imgtool_image       base;
60   imgtool_stream       *file_handle;
61   int       size;
62   UINT8      *data;
63   int       count;
64   TAP_ENTRY    *entries;
65   } TAP_IMAGE;
66
67typedef struct
68   {
69   imgtool_directory    base;
70   TAP_IMAGE   *image;
71   int         index;
72   } TAP_ITERATOR;
73
74static int vmsx_tap_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
75static void vmsx_tap_image_exit(imgtool_image *img);
76static int vmsx_tap_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
77static int vmsx_tap_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
78static void vmsx_tap_image_closeenum(imgtool_directory *enumeration);
79static int vmsx_tap_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
80
81IMAGEMODULE(
82   vmsx_tap,
83   "Virtual MSX Tape archive",      /* human readable name */
84   "tap",                        /* file extension */
85   NULL,                        /* crcfile */
86   NULL,                        /* crc system name */
87   NULL,                        /* eoln */
88   0,                           /* flags */
89   vmsx_tap_image_init,            /* init function */
90   vmsx_tap_image_exit,            /* exit function */
91   NULL,                        /* info function */
92   vmsx_tap_image_beginenum,         /* begin enumeration */
93   vmsx_tap_image_nextenum,         /* enumerate next */
94   vmsx_tap_image_closeenum,         /* close enumeration */
95   NULL,                        /* free space on image */
96   vmsx_tap_image_readfile,         /* read file */
97   NULL,/* write file */
98   NULL,/* delete file */
99   NULL,/* create image */
100   NULL,
101   NULL,
102   NULL,
103   NULL
104)
105
106static const UINT8 CasHeader[8] = { 0x1F,0xA6,0xDE,0xBA,0xCC,0x13,0x7D,0x74 };
107
108
109static int vmsx_tap_read_image (TAP_IMAGE *image)
110   {
111   unsigned char *p, *pmem;
112    unsigned int pos, i, size;
113   UINT32 offset;
114
115   pmem = image->data;
116    size = image->size;
117    pos = 0;
118    while ( (pos + 8) < size)
119      {
120      offset = *((UINT32*)(pmem + pos + 4));
121      offset = LITTLE_ENDIANIZE_INT32 (offset);
122      if (strncmp ((char*)pmem + pos, "INFO", 4) )
123         {
124         /* not this chunk, skip */
125         if (offset & 1) offset++; /* pad byte */
126         pos += offset + 8;
127         continue;
128         }
129      /* found it */
130      pos += 8;
131      p = pmem + pos;
132      /* intregity check */
133      if ( (offset + pos) > size)
134         return IMGTOOLERR_CORRUPTIMAGE;
135      if (p[0] != 0 || p[1] != 1)
136         return IMGTOOLERR_CORRUPTIMAGE;
137
138        image->count = p[2] + p[3] * 256;
139      p += 4;
140      if (offset < (image->count * (32 + 10 + 4) + 4) )
141         return IMGTOOLERR_CORRUPTIMAGE;
142
143      image->entries = (TAP_ENTRY*)malloc (
144         sizeof (TAP_ENTRY) * image->count);
145      if (!image->entries)
146         return IMGTOOLERR_OUTOFMEMORY;
147
148      for (i=0;i<image->count;i++)
149         {
150         /* this should really check the data */
151         strncpy (image->entries[i].title, (char*)p, 32); p += 32;
152         strncpy (image->entries[i].type, (char*)p, 10); p += 10;
153         memcpy (image->entries[i].chunk, (char*)p, 4); p += 4;
154         }
155
156      return 0;
157      }   
158
159   return IMGTOOLERR_MODULENOTFOUND;
160   }
161
162static int vmsx_tap_image_read_data (TAP_IMAGE *image, char *chunk, unsigned char **pcas, int *psize)
163   {
164   unsigned int caspos, pos = 0, found = 0, offset, size, tappos;
165   UINT32 tapblock;
166   unsigned char *p, *pmem;
167
168   size = image->size;
169   pmem = image->data;
170
171    while ( (pos + 8) < size)
172      {
173      offset = *((UINT32*)(pmem + pos + 4));
174      offset = LITTLE_ENDIANIZE_INT32 (offset);
175      if (memcmp (pmem + pos, "LIST", 4) )
176         {
177         if (offset & 1) offset++;
178         pos += offset + 8;
179         continue;
180         }
181
182      if (memcmp (pmem + pos + 8, "TAPE", 4) )
183         return IMGTOOLERR_CORRUPTIMAGE;
184
185      pos += 12;
186      offset -= 8;
187      if ( (pos + offset) > size)
188         return IMGTOOLERR_CORRUPTIMAGE;
189
190      pmem += pos;
191      size = offset;
192      found = 1;
193      break;
194      }
195
196    if (!found)
197      return IMGTOOLERR_CORRUPTIMAGE;
198
199   /* OK we've got the right data chunk. Now we can start looking for
200      the blocks */
201   pos = 0;
202   while ( (pos + 8) < size)
203      {
204      offset = *((UINT32*)(pmem + pos + 4));
205      offset = LITTLE_ENDIANIZE_INT32 (offset);
206      if (memcmp (pmem + pos, chunk, 4) )
207         {
208         if (offset & 1) offset++;
209         pos += offset + 8;
210         continue;
211         }
212
213      pos += 8;
214      caspos = tappos = 0;
215      p = malloc (offset * 2);
216      if (!p) return IMGTOOLERR_OUTOFMEMORY;
217
218      while ( (tappos + 4) <= offset)
219         {
220         tapblock = *((UINT32*)(pmem + pos + tappos));
221         tappos += 4;
222         tapblock = LITTLE_ENDIANIZE_INT32 (tapblock);
223         if (tapblock == 0xffffffff) break;
224         memcpy (p + caspos, CasHeader, 8);
225         caspos += 8;
226         memcpy (p + caspos, pmem + pos + tappos, tapblock);
227         caspos += tapblock;
228         tappos += tapblock;
229         }
230
231
232      *psize = caspos;
233      *pcas = p;
234   
235      return 0;
236      }
237
238   return IMGTOOLERR_CORRUPTIMAGE;
239   }
240
241static int vmsx_tap_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
242{
243   TAP_IMAGE *image;
244   int rc;
245
246   image = (TAP_IMAGE*)malloc (sizeof (TAP_IMAGE) );
247   if (!image) return IMGTOOLERR_OUTOFMEMORY;
248
249   *outimg = (imgtool_image*)image;
250
251   memset(image, 0, sizeof(TAP_IMAGE));
252   image->base.module = mod;
253   image->size=stream_size(f);
254   image->file_handle=f;
255
256   image->data = (UINT8*) malloc(image->size);
257   if (!image->data)
258   {
259      free(image);
260      *outimg=NULL;
261      return IMGTOOLERR_OUTOFMEMORY;
262   }
263
264   if (stream_read(f, image->data, image->size)!=image->size)
265   {
266      free(image);
267      *outimg=NULL;
268      return IMGTOOLERR_READERROR;
269   }
270
271   if ( (rc=vmsx_tap_read_image(image)) )   
272   {
273      if (image->entries) free(image->entries);
274      free(image);
275      *outimg=NULL;
276      return rc;
277   }
278
279   return 0;
280}
281
282static void vmsx_tap_image_exit(imgtool_image *img)
283{
284   TAP_IMAGE *image=(TAP_IMAGE*)img;
285   stream_close(image->file_handle);
286   free(image->entries);
287   free(image->data);
288   free(image);
289}
290
291static int vmsx_tap_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
292{
293   TAP_IMAGE *image=(TAP_IMAGE*)img;
294   TAP_ITERATOR *iter;
295
296   iter=*(TAP_ITERATOR**)outenum = (TAP_ITERATOR*) malloc(sizeof(TAP_ITERATOR));
297   if (!iter)
298      return IMGTOOLERR_OUTOFMEMORY;
299
300   iter->base.module = img->module;
301
302   iter->image=image;
303   iter->index = 0;
304   return 0;
305}
306
307static int vmsx_tap_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
308   {
309   TAP_ITERATOR *iter=(TAP_ITERATOR*)enumeration;
310   unsigned char *p;
311   int size, rc;
312   
313   ent->eof=iter->index>=iter->image->count;
314   if (!ent->eof)
315      {
316      sprintf (ent->fname, "%s-%s.cas",
317         iter->image->entries[iter->index].title,
318         iter->image->entries[iter->index].type);
319      size = 0;
320      p = NULL;
321      rc = vmsx_tap_image_read_data (iter->image,
322         iter->image->entries[iter->index].chunk, &p, &size);
323
324      ent->corrupt=rc;
325      if (!rc) ent->filesize = size;
326      iter->index++;
327
328      if (p) free (p);
329      }
330
331   return 0;
332   }
333
334static void vmsx_tap_image_closeenum(imgtool_directory *enumeration)
335   {
336   free (enumeration);
337   }
338
339static TAP_ENTRY* vmsx_tap_image_findfile(TAP_IMAGE *image, const char *fname)
340   {
341   int i;
342   char filename[64]; /* that's always enough! */
343
344   for (i=0; i<image->count; i++)
345      {
346      sprintf (filename, "%s-%s.cas",
347         image->entries[i].title, image->entries[i].type);
348      if (!strcmp(fname, filename) ) return image->entries+i;
349      }
350   return NULL;
351   }
352
353static int vmsx_tap_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
354   {
355   TAP_IMAGE *image=(TAP_IMAGE*)img;
356   TAP_ENTRY *entry;
357   unsigned char* p;
358   int size, rc;
359
360   if ((entry=vmsx_tap_image_findfile(image, fname))==NULL )
361      return IMGTOOLERR_MODULENOTFOUND;
362
363   rc = vmsx_tap_image_read_data (image, entry->chunk, &p, &size);
364   if (!rc)
365      {
366      if (stream_write(destf, p, size)!=size)
367         {
368         free (p);
369         return IMGTOOLERR_WRITEERROR;
370         }
371      }
372
373    free (p);
374
375   return rc;
376   }
377
src/mess/tools/imgtool/modules/d64.h
r0r1340
1void d64_open_helper (void);
2int cbm_compareNames (const unsigned char *left, const unsigned char *right);
3
src/mess/tools/imgtool/modules/vmsx_gm2.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6
7/*
8   vMSX gmaster2.ram
9
10   Virtual MSX 1.x (being replaced by the MSX driver in mess) had
11   it's on format for Konami's Game Master 2 SRAM. The file was
12   always saved as gmaster2.ram; however the file was 16kB when
13   the actual data is 8kB. 8kB is redundant, which is not used
14   by MESS, Virtual MSX 2.0 (never finished), and the patches for
15   fMSX written by me (Sean Young). So suppose you'd like to use
16   the SRAM from Virtual MSX, use this very simple converter.
17
18*/
19
20#define NewName "gmaster2.mem"
21
22typedef struct {
23   imgtool_image         base;
24   imgtool_stream          *file_handle;
25   int          size;
26   unsigned char   *data;
27   int          count;
28   } GM2_IMAGE;
29
30typedef struct
31   {
32   imgtool_directory    base;
33   GM2_IMAGE   *image;
34   int         index;
35   } TAP_ITERATOR;
36
37static int vmsx_gm2_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
38static void vmsx_gm2_image_exit(imgtool_image *img);
39//static void vmsx_gm2_image_info(imgtool_image *img, char *string, const int len);
40static int vmsx_gm2_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
41static int vmsx_gm2_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
42static void vmsx_gm2_image_closeenum(imgtool_directory *enumeration);
43static int vmsx_gm2_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
44
45IMAGEMODULE(
46   vmsx_gm2,
47   "Virtual MSX Game Master 2 SRAM",      /* human readable name */
48   "ram",                        /* file extension */
49   NULL,                        /* crcfile */
50   NULL,                        /* crc system name */
51   NULL,                        /* eoln */
52   0,                           /* flags */
53   vmsx_gm2_image_init,            /* init function */
54   vmsx_gm2_image_exit,            /* exit function */
55   NULL,                        /* info function */
56   vmsx_gm2_image_beginenum,         /* begin enumeration */
57   vmsx_gm2_image_nextenum,         /* enumerate next */
58   vmsx_gm2_image_closeenum,         /* close enumeration */
59   NULL,                        /* free space on image */
60   vmsx_gm2_image_readfile,         /* read file */
61   NULL,/* write file */
62   NULL,/* delete file */
63   NULL,/* create image */
64   NULL,                        /* read sector */
65   NULL,                        /* write sector */
66   NULL,               /* file options */
67   NULL               /* create options */
68)
69
70static int vmsx_gm2_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
71{
72   GM2_IMAGE *image;
73
74   image = (GM2_IMAGE*)malloc (sizeof (GM2_IMAGE) );
75   if (!image) return IMGTOOLERR_OUTOFMEMORY;
76
77   *outimg = (imgtool_image*)image;
78
79   memset(image, 0, sizeof(GM2_IMAGE));
80   image->base.module = mod;
81   image->size=stream_size(f);
82   image->file_handle=f;
83
84    if (image->size != 0x4000)
85   {
86      free (image);
87      return IMGTOOLERR_READERROR;
88   }
89
90   image->data = (unsigned char *) malloc(image->size);
91   if ( (!image->data)
92       ||(stream_read(f, image->data, image->size)!=image->size) )
93   {
94      free(image);
95      *outimg=NULL;
96      return IMGTOOLERR_OUTOFMEMORY;
97   }
98
99   return 0;
100}
101
102static void vmsx_gm2_image_exit(imgtool_image *img)
103   {
104   GM2_IMAGE *image=(GM2_IMAGE*)img;
105   stream_close(image->file_handle);
106   free(image->data);
107   free(image);
108   }
109
110static int vmsx_gm2_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
111   {
112   GM2_IMAGE *image=(GM2_IMAGE*)img;
113   TAP_ITERATOR *iter;
114
115   iter=*(TAP_ITERATOR**)outenum = (TAP_ITERATOR*) malloc(sizeof(TAP_ITERATOR));
116   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
117
118   iter->base.module = img->module;
119
120   iter->image=image;
121   iter->index = 0;
122   return 0;
123   }
124
125static int vmsx_gm2_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
126   {
127   TAP_ITERATOR *iter=(TAP_ITERATOR*)enumeration;
128
129   ent->eof=iter->index;
130   if (!ent->eof)
131      {
132      strcpy (ent->fname, NewName);
133      ent->corrupt=0;
134      ent->filesize = 0x2000;
135      iter->index++;
136      }
137
138   return 0;
139   }
140
141static void vmsx_gm2_image_closeenum(imgtool_directory *enumeration)
142   {
143   free(enumeration);
144   }
145
146static int vmsx_gm2_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
147   {
148   GM2_IMAGE *image=(GM2_IMAGE*)img;
149
150   if (mame_stricmp (fname, NewName) )
151      return IMGTOOLERR_MODULENOTFOUND;
152
153   if (stream_write(destf, image->data + 0x1000, 0x1000)!=0x1000)
154         return IMGTOOLERR_WRITEERROR;
155
156   if (stream_write(destf, image->data + 0x3000, 0x1000)!=0x1000)
157         return IMGTOOLERR_WRITEERROR;
158
159   return 0;
160   }
161
src/mess/tools/imgtool/modules/macutil.h
r0r1340
1/****************************************************************************
2
3   macutil.h
4
5   Imgtool Utility code for manipulating certain Apple/Mac data structures
6   and conventions
7
8*****************************************************************************/
9
10#ifndef MACUTIL_H
11#define MACUTIL_H
12
13#include "imgtool.h"
14
15typedef enum
16{
17   MAC_FORK_DATA,
18   MAC_FORK_RESOURCE
19} mac_fork_t;
20
21typedef enum
22{
23   MAC_FILECATEGORY_DATA,
24   MAC_FILECATEGORY_TEXT,
25   MAC_FILECATEGORY_FORKED
26} mac_filecategory_t;
27
28
29/* converting Classic Mac OS time <==> Imgtool time */
30time_t mac_crack_time(UINT32 t);
31UINT32 mac_setup_time(time_t t);
32UINT32 mac_time_now(void);
33
34imgtoolerr_t mac_identify_fork(const char *fork_string, mac_fork_t *fork_num);
35
36void mac_suggest_transfer(mac_filecategory_t file_category, imgtool_transfer_suggestion *suggestions, size_t suggestions_length);
37
38void pascal_from_c_string(unsigned char *pstring, size_t pstring_len, const char *cstring);
39
40#endif /* MACUTIL_H */
src/mess/tools/imgtool/modules/fmsx_cas.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "formats/fmsx_cas.h"
6#include "imgtoolx.h"
7#include "utils.h"
8
9/*
10   MSX module
11
12   fMSX style .cas for the MSX. Converts them to .wav files. Uses the
13   mess/formats/fmsx_cas.[ch] files, for the actual conversion.
14*/
15
16typedef struct {
17   imgtool_image         base;
18   char         *file_name;
19   imgtool_stream          *file_handle;
20   int          size;
21   unsigned char   *data;
22   int          count;
23   } CAS_IMAGE;
24
25typedef struct
26   {
27   imgtool_directory    base;
28   CAS_IMAGE   *image;
29   int         index;
30   } CAS_ITERATOR;
31
32static int fmsx_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
33static void fmsx_cas_image_exit(imgtool_image *img);
34//static void fmsx_cas_image_info(imgtool_image *img, char *string, const int len);
35static int fmsx_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
36static int fmsx_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
37static void fmsx_cas_image_closeenum(imgtool_directory *enumeration);
38static int fmsx_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
39
40IMAGEMODULE(
41   fmsx_cas,
42   "fMSX style .cas file",            /* human readable name */
43   "cas",                        /* file extension */
44   NULL,                        /* crcfile */
45   NULL,                        /* crc system name */
46   NULL,                        /* eoln */
47   0,                           /* flags */
48   fmsx_cas_image_init,            /* init function */
49   fmsx_cas_image_exit,            /* exit function */
50   NULL,                        /* info function */
51   fmsx_cas_image_beginenum,         /* begin enumeration */
52   fmsx_cas_image_nextenum,         /* enumerate next */
53   fmsx_cas_image_closeenum,         /* close enumeration */
54   NULL,                        /* free space on image */
55   fmsx_cas_image_readfile,         /* read file */
56   NULL,/* write file */
57   NULL,/* delete file */
58   NULL,/* create image */
59   NULL,                        /* read sector */
60   NULL,                        /* write sector */
61   NULL,               /* file options */
62   NULL               /* create options */
63)
64
65static int fmsx_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
66   {
67   CAS_IMAGE *image;
68   int len;
69   char *pbase;
70   char default_name[] = "msxtape";
71
72   image = (CAS_IMAGE*)malloc (sizeof (CAS_IMAGE) );
73   if (!image) return IMGTOOLERR_OUTOFMEMORY;
74
75   *outimg = (imgtool_image*)image;
76
77   memset(image, 0, sizeof(CAS_IMAGE));
78   image->base.module = mod;
79   image->size=stream_size(f);
80   image->file_handle=f;
81
82    if (image->size < 9)
83      {
84      free (image);
85      return IMGTOOLERR_CORRUPTIMAGE;
86      }
87
88   image->data = (unsigned char *) malloc(image->size);
89   if (!image->data || (stream_read(f, image->data, image->size)!=image->size) )
90   {
91      free(image);
92      *outimg=NULL;
93      return IMGTOOLERR_OUTOFMEMORY;
94   }
95
96     if ( (image->count = fmsx_cas_to_wav_size (image->data, image->size) ) < 0)
97      {
98      free(image->data);
99      free(image);
100      *outimg=NULL;
101      return IMGTOOLERR_CORRUPTIMAGE;
102      }
103
104   pbase = NULL;
105    if (pbase) len = strlen (pbase);
106    else len = strlen (default_name);
107
108    image->file_name = malloc (len + 5);
109   if (!image->file_name)
110      {
111      free(image->data);
112      free(image);
113      *outimg=NULL;
114      return IMGTOOLERR_CORRUPTIMAGE;
115      }
116
117    if (!pbase)
118      strcpy (image->file_name, default_name);
119    else
120      {
121      strcpy (image->file_name, pbase);
122        if (len > 4)
123         if (!strncmpi (".cas", image->file_name + len - 4, 4) ) len -= 4;
124
125      strcpy (image->file_name + len, ".wav");
126      }
127
128   return 0;
129   }
130
131static void fmsx_cas_image_exit(imgtool_image *img)
132   {
133   CAS_IMAGE *image=(CAS_IMAGE*)img;
134   stream_close(image->file_handle);
135   free(image->file_name);
136   free(image->data);
137   free(image);
138   }
139
140static int fmsx_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
141{
142   CAS_IMAGE *image=(CAS_IMAGE*)img;
143   CAS_ITERATOR *iter;
144
145   iter=*(CAS_ITERATOR**)outenum = (CAS_ITERATOR*) malloc(sizeof(CAS_ITERATOR));
146   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
147
148   iter->base.module = img->module;
149
150   iter->image=image;
151   iter->index = 0;
152   return 0;
153}
154
155static int fmsx_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
156{
157   CAS_ITERATOR *iter=(CAS_ITERATOR*)enumeration;
158
159   ent->eof=iter->index;
160   if (!ent->eof)
161   {
162      strcpy (ent->fname, iter->image->file_name);
163      ent->corrupt=0;
164      ent->filesize = iter->image->count * 2 + 0x2c;
165      iter->index++;
166   }
167
168   return 0;
169}
170
171static void fmsx_cas_image_closeenum(imgtool_directory *enumeration)
172{
173   free(enumeration);
174}
175
176static int fmsx_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
177   {
178   CAS_IMAGE *image=(CAS_IMAGE*)img;
179   INT16 *wavdata;
180   UINT16   temp16;
181   UINT32   temp32;
182   int wavlen, offset, rc;
183
184   if (mame_stricmp (fname, image->file_name) )
185      return IMGTOOLERR_MODULENOTFOUND;
186
187   rc = fmsx_cas_to_wav(image->data, image->size, &wavdata, &wavlen);
188   if (rc == 2)
189      return IMGTOOLERR_OUTOFMEMORY;
190   else if (rc)
191      return IMGTOOLERR_CORRUPTIMAGE;
192
193   if (wavlen != image->count)
194      {
195      free (wavdata);
196      return IMGTOOLERR_UNEXPECTED;
197      }
198
199    /* write the core header for a WAVE file */
200   offset = stream_write(destf, "RIFF", 4);
201    if( offset < 4 )
202       {
203      free(wavdata);
204      return IMGTOOLERR_WRITEERROR;
205       }
206
207   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2 + 0x24);
208   offset += stream_write(destf, &temp32, 4);
209    if( offset < 8 )
210       {
211      free(wavdata);
212      return IMGTOOLERR_WRITEERROR;
213       }
214
215   /* read the RIFF file type and make sure it's a WAVE file */
216   offset += stream_write(destf, "WAVEfmt ", 8);
217   if( offset < 16 )
218       {
219      free(wavdata);
220      return IMGTOOLERR_WRITEERROR;
221      }
222
223    /* size of the following 'fmt ' fields */
224    offset += stream_write(destf, "\x10\x00\x00\x00", 4);
225   if( offset < 20 )
226       {
227      free(wavdata);
228      return IMGTOOLERR_WRITEERROR;
229      }
230
231   /* format: PCM */
232   temp16 = LITTLE_ENDIANIZE_INT16 (1);
233   offset += stream_write(destf, &temp16, 2);
234   if( offset < 22 )
235       {
236      free(wavdata);
237      return IMGTOOLERR_WRITEERROR;
238      }
239
240   /* channels: 1 (mono) */
241   temp16 = LITTLE_ENDIANIZE_INT16 (1);
242   offset += stream_write(destf, &temp16, 2);
243   if( offset < 24 )
244       {
245      free(wavdata);
246      return IMGTOOLERR_WRITEERROR;
247      }
248
249   /* sample rate */
250   temp32 = LITTLE_ENDIANIZE_INT32(22050);
251   offset += stream_write(destf, &temp32, 4);
252   if( offset < 24 )
253       {
254      free(wavdata);
255      return IMGTOOLERR_WRITEERROR;
256      }
257
258   /* byte rate */
259   temp32 = LITTLE_ENDIANIZE_INT32(22050 * 2);
260   offset += stream_write(destf, &temp32, 4);
261   if( offset < 28 )
262       {
263      free(wavdata);
264      return IMGTOOLERR_WRITEERROR;
265      }
266
267   /* block align (size of one `sample') */
268   temp16 = LITTLE_ENDIANIZE_INT16 (2);
269   offset += stream_write(destf, &temp16, 2);
270   if( offset < 30 )
271       {
272      free(wavdata);
273      return IMGTOOLERR_WRITEERROR;
274      }
275
276   /* block align */
277   temp16 = LITTLE_ENDIANIZE_INT16 (16);
278   offset += stream_write(destf, &temp16, 2);
279   if( offset < 32 )
280       {
281      free(wavdata);
282      return IMGTOOLERR_WRITEERROR;
283      }
284
285   /* 'data' tag */
286   offset += stream_write(destf, "data", 4);
287   if( offset < 36 )
288       {
289      free(wavdata);
290      return IMGTOOLERR_WRITEERROR;
291      }
292
293   /* data size */
294   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2);
295   offset += stream_write(destf, &temp32, 4);
296   if( offset < 40 )
297       {
298      free(wavdata);
299      return IMGTOOLERR_WRITEERROR;
300      }
301
302   if (stream_write(destf, wavdata, (image->count*2))!=(image->count*2))
303       {
304      free(wavdata);
305      return IMGTOOLERR_WRITEERROR;
306      }
307
308   free (wavdata);
309
310   return 0;
311   }
312
src/mess/tools/imgtool/modules/rom16.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "zlib.h"
5#include "osdepend.h"
6#include "imgtoolx.h"
7
8typedef struct {
9   imgtool_image base;
10   imgtool_stream *file_handle;
11   int size;
12   int modified;
13   unsigned char *data;
14} rom16_image;
15
16typedef struct {
17   imgtool_directory base;
18   rom16_image *image;
19   int index;
20} rom16_iterator;
21
22static int rom16_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
23static void rom16_image_exit(imgtool_image *img);
24//static void rom16_image_info(imgtool_image *img, char *string, const int len);
25static int rom16_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
26static int rom16_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
27static void rom16_image_closeenum(imgtool_directory *enumeration);
28static int rom16_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
29static int rom16_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
30//static int rom16_image_create(imgtool_stream *f, const geometry_options *options_);
31
32IMAGEMODULE(
33   rom16,
34   "16 bit wide Romimage",   /* human readable name */
35   "rom",                        /* file extension */
36   NULL,                        /* crcfile */
37   NULL,                        /* crc system name */
38   NULL,                        /* eoln */
39   0,                           /* flags */
40   rom16_image_init,            /* init function */
41   rom16_image_exit,            /* exit function */
42   NULL, /* info function */
43   rom16_image_beginenum,         /* begin enumeration */
44   rom16_image_nextenum,         /* enumerate next */
45   rom16_image_closeenum,         /* close enumeration */
46   NULL, //crt_image_freespace,         /* free space on image */
47   rom16_image_readfile,         /* read file */
48   rom16_image_writefile,         /* write file */
49   NULL,         /* delete file */
50   NULL,//   rom16_image_create,            /* create image */
51   NULL,
52   NULL,
53   NULL,                     /* file options */
54   NULL                     /* create options */
55)
56
57static int rom16_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
58{
59   rom16_image *image;
60
61   image=*(rom16_image**)outimg=(rom16_image *) malloc(sizeof(rom16_image));
62   if (!image) return IMGTOOLERR_OUTOFMEMORY;
63
64   memset(image, 0, sizeof(rom16_image));
65   image->base.module = mod;
66   image->size=stream_size(f);
67   image->file_handle=f;
68
69   image->data = (unsigned char *) malloc(image->size);
70   if ( (!image->data)
71       ||(stream_read(f, image->data, image->size)!=image->size) ) {
72      free(image);
73      *outimg=NULL;
74      return IMGTOOLERR_OUTOFMEMORY;
75   }
76
77   return 0;
78}
79
80static void rom16_image_exit(imgtool_image *img)
81{
82   rom16_image *image=(rom16_image*)img;
83   if (image->modified) {
84      stream_clear(image->file_handle);
85      stream_write(image->file_handle, image->data, image->size);
86   }
87   stream_close(image->file_handle);
88   free(image->data);
89   free(image);
90}
91
92#if 0
93static void rom16_image_info(imgtool_image *img, char *string, const int len)
94{
95   _image *image=(rom16_image*)img;
96   sprintf(string, "%-32s\nversion:%.4x type:%d:%s exrom:%d game:%d",
97         HEADER(image)->name,
98         GET_UWORD(HEADER(image)->version),
99         GET_UWORD(HEADER(image)->hardware_type),
100         hardware_types[GET_UWORD(HEADER(image)->hardware_type)],
101         HEADER(image)->exrom_line, HEADER(image)->game_line);
102   return;
103}
104#endif
105
106static int rom16_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
107{
108   rom16_image *image=(rom16_image*)img;
109   rom16_iterator *iter;
110
111   iter=*(rom16_iterator**)outenum = (rom16_iterator *) malloc(sizeof(rom16_iterator));
112   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
113
114   iter->base.module = img->module;
115
116   iter->image=image;
117   iter->index = 0;
118   return 0;
119}
120
121static int rom16_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
122{
123    int pos = 0;
124   rom16_iterator *iter=(rom16_iterator*)enumeration;
125
126   ent->corrupt=0;
127   ent->eof=0;
128
129   switch (iter->index) {
130   case 0:
131       pos=0;
132       strcpy(ent->fname,"even");
133       ent->filesize= iter->image->size/2;
134       iter->index++;
135       break;
136   case 1:
137       pos=1;
138       iter->index++;
139       ent->filesize= iter->image->size/2;
140       strcpy(ent->fname,"odd");
141       break;
142   default:
143       ent->eof=1;
144   }
145   if (ent->eof==0 && ent->attr) {
146       unsigned crc=0;
147       for (;pos<iter->image->size; pos+=2) {
148      crc=crc32(crc, iter->image->data+pos, 1);
149       }
150       sprintf(ent->attr, "0x%x", crc);
151   }
152   return 0;
153}
154
155static void rom16_image_closeenum(imgtool_directory *enumeration)
156{
157   free(enumeration);
158}
159
160static int rom16_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
161{
162   rom16_image *image=(rom16_image*)img;
163   int pos;
164   int i;
165
166   if (mame_stricmp(fname, "even")==0) {
167      pos=0;
168   } else if (mame_stricmp(fname,"odd")==0) {
169      pos=1;
170   } else {
171      return IMGTOOLERR_MODULENOTFOUND;
172   }
173
174   for (i=0; i<image->size; i+=2) {
175      if (stream_write(destf, image->data+pos+i, 1)!=1)
176         return IMGTOOLERR_WRITEERROR;
177   }
178
179   return 0;
180}
181
182static int rom16_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef,
183                        const ResolvedOption *options_)
184{
185   rom16_image *image=(rom16_image*)img;
186   int size;
187   int pos;
188   int i;
189
190   size=stream_size(sourcef);
191   if (size*2!=image->size) return IMGTOOLERR_READERROR;
192   if (mame_stricmp(fname, "even")==0) {
193      pos=0;
194   } else if (mame_stricmp(fname,"odd")==0) {
195      pos=1;
196   } else {
197      return IMGTOOLERR_MODULENOTFOUND;
198   }
199
200   for (i=0; i<size; i++) {
201      if (stream_read(sourcef, image->data+pos+i*2, 1)!=1)
202         return IMGTOOLERR_READERROR;
203   }
204   image->modified=1;
205
206   return 0;
207}
208
209#if 0
210static int rom16_image_create(imgtool_stream *f, const ResolvedOption *options_)
211{
212//   if (options_->label) strcpy(header.name, options->label);
213   return (stream_write(f, &header, sizeof(crt_header)) == sizeof(crt_header))
214      ? 0 : IMGTOOLERR_WRITEERROR;
215}
216#endif
src/mess/tools/imgtool/modules/vzdos.c
r0r1340
1/****************************************************************************
2
3   vzdos.c
4
5   Laser/VZ disk images
6
7****************************************************************************/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <math.h>
13#include "osdepend.h"
14#include "imgtool.h"
15#include "imgtoolx.h"
16#include "utils.h"
17#include "formats/vt_dsk.h"
18#include "iflopimg.h"
19
20/*
21
22sector format
23
24| GAP1 | IDAM | GAP2 | DATA | CHECKSUM | ...
25
26GAP1     = 80 80 80 80 80 00                                         6
27IDAM     = FE E7 18 C3 Track# Sector# Checksum-8 of prev. 2 bytes    7
28GAP2     = 80 80 80 80 80 80 00 C3 18 E7 FE                         11
29DATA     = 126 bytes actual data                                   126
30         = nextTrack# nextSector#                                    2
31CHECKSUM = Checksum-16 of the previous 128 bytes                     2
32                                                                   ---
33                                                                   154 bytes
34
35sectors 0 to 14 are used for the disk directory. sector 15 is used
36as track map, with one bit for each sector used.
37
38*/
39
40#define DATA_SIZE   (126)
41#define SECTOR_SIZE   (0x9a)
42#define MAX_DIRENTS   (15*8)
43
44/* vzdos directry entry */
45typedef struct vzdos_dirent
46{
47   char ftype;
48   char delimitor;
49   char fname[8];
50   UINT8 start_track;
51   UINT8 start_sector;
52   UINT16 start_address;
53   UINT16 end_address;
54} vzdos_dirent;
55
56typedef struct vz_iterator
57{
58   int index;
59   int eof;
60} vz_iterator;
61
62static const UINT8 sector_order[] =
63{
64   0, 3, 6, 9, 12, 15, 2, 5, 8, 11, 14, 1, 4, 7, 10, 13
65};
66
67/*********************************************************************
68   Internal functions
69*********************************************************************/
70
71/* get length of filename without trailing spaces */
72static int vzdos_get_fname_len(const char *fname)
73{
74   int len;
75
76   for (len = 7; len > 0; len--)         
77      if (fname[len] != 0x20)
78         break;
79   
80   return len;   
81}
82
83/* calculate checksum-16 of buffer */
84static UINT16 chksum16(UINT8 *buffer, int len)
85{
86   int i;
87   UINT16 sum = 0;
88   
89   for (i = 0; i < len; i++)
90      sum += buffer[i];   
91   
92   return sum;
93}
94
95/* returns the offset where the actual sector data starts */
96static imgtoolerr_t vzdos_get_data_start(imgtool_image *img, int track, int sector, int *start)
97{
98   imgtoolerr_t ret;
99   UINT8 buffer[25]; /* enough to read the sector header */
100
101   ret = floppy_read_sector(imgtool_floppy(img), 0, track, sector_order[sector], 0, &buffer, sizeof(buffer));
102   if (ret) return ret;
103     
104   /* search for start of data */
105   if (memcmp(buffer + 19, "\xC3\x18\xE7\xFE", 4) == 0)
106      *start = 23;
107   else if (memcmp(buffer + 20, "\xC3\x18\xE7\xFE", 4) == 0)
108      *start = 24;
109   else if (memcmp(buffer + 21, "\xC3\x18\xE7\xFE", 4) == 0)
110      *start = 25;
111   else
112      return IMGTOOLERR_CORRUPTIMAGE;
113
114   return IMGTOOLERR_SUCCESS;
115}
116
117/* return the actual data of a sector */
118static imgtoolerr_t vzdos_read_sector_data(imgtool_image *img, int track, int sector, UINT8 *data)
119{
120   int ret, data_start;
121   UINT8 buffer[DATA_SIZE + 4]; /* data + checksum */
122
123   ret = vzdos_get_data_start(img, track, sector, &data_start);
124   if (ret) return ret;
125
126   ret = floppy_read_sector(imgtool_floppy(img), 0, track, sector_order[sector], data_start, &buffer, sizeof(buffer));
127   if (ret) return ret;
128
129   /* verify sector checksums */
130   if (pick_integer_le(buffer, DATA_SIZE + 2, 2) != chksum16(buffer, DATA_SIZE + 2))
131      return IMGTOOLERR_CORRUPTFILE;
132
133   memcpy(data, &buffer, DATA_SIZE + 2);
134   
135   return IMGTOOLERR_SUCCESS;
136}
137
138/* write data to sector */
139static imgtoolerr_t vzdos_write_sector_data(imgtool_image *img, int track, int sector, UINT8 *data)
140{
141   int ret, data_start;
142   UINT8 buffer[DATA_SIZE + 4]; /* data + checksum */
143
144   ret = vzdos_get_data_start(img, track, sector, &data_start);
145   if (ret) return ret;
146
147   memcpy(buffer, data, DATA_SIZE + 2);
148   place_integer_le(buffer, DATA_SIZE + 2, 2, chksum16(data, DATA_SIZE + 2));
149   
150   ret = floppy_write_sector(imgtool_floppy(img), 0, track, sector_order[sector], data_start, buffer, sizeof(buffer));
151   if (ret) return ret;
152   
153   return IMGTOOLERR_SUCCESS;
154}
155
156/* write formatted empty sector */
157static imgtoolerr_t vzdos_clear_sector(imgtool_image *img, int track, int sector)
158{
159   UINT8 data[DATA_SIZE + 2];
160   
161   memset(data, 0x00, sizeof(data));
162   
163   return vzdos_write_sector_data(img, track, sector, data);   
164}
165
166/* return a directory entry for an index */
167static imgtoolerr_t vzdos_get_dirent(imgtool_image *img, int index, vzdos_dirent *ent)
168{
169   int ret, entry;
170   UINT8 buffer[DATA_SIZE + 2];
171
172   ret = vzdos_read_sector_data(img, 0, (int) index / 8, buffer);
173   if (ret) return ret;
174   
175   entry = ((index % 8) * sizeof(vzdos_dirent));
176
177   memcpy(ent, &buffer[entry], 10);
178   ent->start_track   = pick_integer_le(&buffer[entry], 10, 1);
179   ent->start_sector  = pick_integer_le(&buffer[entry], 11, 1);
180   ent->start_address = pick_integer_le(&buffer[entry], 12, 2);
181   ent->end_address   = pick_integer_le(&buffer[entry], 14, 2);
182
183   if (ent->ftype == 0x00)
184      return IMGTOOLERR_FILENOTFOUND;
185
186   /* check values */
187   if (ent->start_track > 39)
188      return IMGTOOLERR_CORRUPTIMAGE;
189     
190   if (ent->start_sector > 15)
191      return IMGTOOLERR_CORRUPTIMAGE;
192
193   return IMGTOOLERR_SUCCESS;
194}
195
196/* save a directory entry to disk */
197static imgtoolerr_t vzdos_set_dirent(imgtool_image *img, int index, vzdos_dirent ent)
198{
199   int ret, entry;
200   UINT8 buffer[DATA_SIZE + 2];
201
202   /* read current sector with entries */
203   ret = vzdos_read_sector_data(img, 0, (int) index / 8, buffer);
204   if (ret) return ret;
205
206   entry = ((index % 8) * sizeof(vzdos_dirent));
207
208   memcpy(&buffer[entry], &ent, 10);
209   place_integer_le(buffer, entry + 10, 1, ent.start_track);
210   place_integer_le(buffer, entry + 11, 1, ent.start_sector);
211   place_integer_le(buffer, entry + 12, 2, ent.start_address);
212   place_integer_le(buffer, entry + 14, 2, ent.end_address);
213   
214   /* save new sector */
215   ret = vzdos_write_sector_data(img, 0, (int) index / 8, buffer);
216   if (ret) return ret;
217   
218   return IMGTOOLERR_SUCCESS;   
219}
220
221/* clear a directory entry */
222static imgtoolerr_t vzdos_clear_dirent(imgtool_image *img, int index)
223{
224   int ret;
225   vzdos_dirent entry;
226
227   memset(&entry, 0x00, sizeof(vzdos_dirent));
228
229   ret = vzdos_set_dirent(img, index, entry);
230   if (ret) return ret;
231     
232   return IMGTOOLERR_SUCCESS;
233}
234
235/* search the index for a directory entry */
236static imgtoolerr_t vzdos_searchentry(imgtool_image *image, const char *fname, int *entry) {
237   int i, len, ret;
238   vzdos_dirent ent;
239   char filename[9];
240
241   /* check for invalid filenames */
242   if (strlen(fname) > 8)
243      return IMGTOOLERR_BADFILENAME;
244     
245   /* TODO: check for invalid characters */
246   
247   *entry = -1;
248     
249   for (i = 0; i < MAX_DIRENTS; i++) {
250
251      ret = vzdos_get_dirent(image, i, &ent);
252      if (ret) return ret;
253     
254      len = vzdos_get_fname_len(ent.fname) + 1;
255
256      if (strlen(fname) != len)
257         continue;
258     
259      memset(filename, 0x00, sizeof(filename));
260      memcpy(filename, ent.fname, len);
261
262      if (!mame_stricmp(fname, filename)) {
263         *entry = i;
264         break;
265      }
266     
267   }
268   
269   if (*entry == -1)
270      return IMGTOOLERR_FILENOTFOUND;
271
272   return IMGTOOLERR_SUCCESS;
273}
274
275/* return a directory entry for a filename */
276static imgtoolerr_t vzdos_get_dirent_fname(imgtool_image *img, const char *fname, vzdos_dirent *ent)
277{
278   int ret, index;
279
280   ret = vzdos_searchentry(img, fname, &index);
281   if (ret) return ret;
282   
283   ret = vzdos_get_dirent(img, index, ent);
284   if (ret) return ret;   
285   
286   return IMGTOOLERR_SUCCESS;
287}
288
289static imgtoolerr_t vzdos_toggle_trackmap(imgtool_image *img, int track, int sector, int clear)
290{
291   int ret, value, bit;
292   UINT8 buffer[DATA_SIZE + 2];
293
294   /* get trackmap from image */
295   ret = vzdos_read_sector_data(img, 0, 15, buffer);
296   if (ret) return ret;
297
298   value = (int) (floor((track * 16 + sector) / 8) - 1);
299   bit   = 0x01 << ((track * 16 + sector) % 8);
300
301   if (clear)
302      buffer[value-1] &= ~bit;
303   else
304      buffer[value-1] |= bit;
305
306   ret = vzdos_write_sector_data(img, 0, 15, buffer);
307   if (ret) return ret;
308     
309   return IMGTOOLERR_SUCCESS;
310}
311
312/* clear a trackmap entry */
313static imgtoolerr_t vzdos_clear_trackmap(imgtool_image *img, int track, int sector)
314{
315   return vzdos_toggle_trackmap(img, track, sector, 1);
316}
317
318/* enable a trackmap entry */
319static imgtoolerr_t vzdos_set_trackmap(imgtool_image *img, int track, int sector)
320{
321   return vzdos_toggle_trackmap(img, track, sector, 0);
322}
323
324/* return the status of a trackmap entry */
325static imgtoolerr_t vzdos_get_trackmap(imgtool_image *img, int track, int sector, int *used)
326{
327   int ret, value, bit;
328   UINT8 buffer[DATA_SIZE + 2];
329
330   /* get trackmap from image */
331   ret = vzdos_read_sector_data(img, 0, 15, buffer);
332   if (ret) return ret;
333
334   value = (int) (floor((track * 16 + sector) / 8) - 1);
335   bit   = 0x01 << ((track * 16 + sector) % 8);
336
337   if (buffer[value-1] & bit)
338      *used = 1;
339   else
340      *used = 0;
341
342   return IMGTOOLERR_SUCCESS;   
343}
344
345/* return the next free sector */
346static imgtoolerr_t vzdos_free_trackmap(imgtool_image *img, int *track, int *sector)
347{
348   int ret, used = 0;
349   
350   for (*track = 1; *track < 40; (*track)++) {
351      for (*sector = 0; *sector < 16; (*sector)++) {
352         ret = vzdos_get_trackmap(img, *track, *sector, &used);
353         if (ret) return ret;
354         if (!used) return IMGTOOLERR_SUCCESS;
355      }   
356   }
357   
358   return IMGTOOLERR_NOSPACE;
359}
360
361static imgtoolerr_t vzdos_write_formatted_sector(imgtool_image *img, int track, int sector)
362{
363   int ret;
364   UINT8 sector_data[DATA_SIZE + 4];
365
366   UINT8 sector_header[24] = {
367      0x80, 0x80, 0x80, 0x80, 0x80, 0x00, 0xFE, 0xE7,
368      0x18, 0xC3, 0x00, 0x00, 0x00, 0x80, 0x80, 0x80,
369      0x80, 0x80, 0x80, 0x00, 0xC3, 0x18, 0xE7, 0xFE
370   };
371   
372   memset(sector_data, 0x00, sizeof(sector_data));
373
374   sector_header[10] = (UINT8) track;         /* current track */
375   sector_header[11] = (UINT8) sector;         /* current sector */
376   sector_header[12] = (UINT8) track + sector;   /* checksum-8 */
377
378   ret = floppy_write_sector(imgtool_floppy(img), 0, track, sector_order[sector], 0, sector_header, sizeof(sector_header));
379   if (ret) return ret;
380
381   ret = floppy_write_sector(imgtool_floppy(img), 0, track, sector_order[sector], sizeof(sector_header), sector_data, sizeof(sector_data));
382   if (ret) return ret;
383
384   return IMGTOOLERR_SUCCESS;
385}
386
387/*********************************************************************
388   Imgtool module code
389*********************************************************************/
390
391static imgtoolerr_t vzdos_diskimage_beginenum(imgtool_directory *enumeration, const char *path)
392{
393   vz_iterator *iter;
394
395   iter = (vz_iterator *) imgtool_directory_extrabytes(enumeration);
396   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
397
398   iter->index = 1;
399   iter->eof = 0;
400
401   return IMGTOOLERR_SUCCESS;
402}
403
404static imgtoolerr_t vzdos_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
405{
406   vz_iterator *iter = (vz_iterator *) imgtool_directory_extrabytes(enumeration);
407
408   if (iter->eof == 1 || iter->index > MAX_DIRENTS) {
409   
410      ent->eof = 1;
411   
412   } else {
413     
414      const char *type;
415      int ret, len;
416      vzdos_dirent dirent;
417
418      ret = vzdos_get_dirent(imgtool_directory_image(enumeration), iter->index - 1, &dirent);
419     
420      if (dirent.ftype == 0x00) {
421         iter->eof = 1;
422         ent->eof = 1;
423         return IMGTOOLERR_SUCCESS;
424      }
425     
426      /* kill trailing spaces */
427      for (len = 7; len > 0; len--) {         
428         if (dirent.fname[len] != 0x20) {
429            break;
430         }
431      }
432     
433      memcpy(ent->filename, &dirent.fname, len + 1);
434      ent->filesize = dirent.end_address - dirent.start_address;
435     
436      switch (dirent.ftype) {
437         case 'T': type = "Basic";      break;
438         case 'B': type = "Binary";     break;
439         case 'D': type = "Data";       break;
440         case 'F': type = "Quickwrite"; break;
441         case 'A': type = "Assembler";  break;
442         case 'S': type = "Diskops";    break;
443         case 'W': type = "Wordpro";    break;
444         default: type = "Unknown";
445      }
446      snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%s", type);
447     
448      iter->index++;   
449   }
450   
451   return IMGTOOLERR_SUCCESS;
452}
453
454/* TRK 0 sector 15 is used to hold the track map of the disk with one bit
455   corresponding to a sector used. */
456static imgtoolerr_t vzdos_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
457{
458   imgtoolerr_t ret;
459   int i;
460   imgtool_image *image = imgtool_partition_image(partition);
461   UINT8 c, v, buffer[DATA_SIZE + 2];
462   *size = 0;
463
464   ret = vzdos_read_sector_data(image, 0, 15, buffer);
465   if (ret) return ret;
466
467   for (i = 0; i < DATA_SIZE; i++) {
468      v = buffer[i];
469      for (c = 0; v; c++) {
470         v &= v - 1;
471      }
472      *size += c * DATA_SIZE;
473   }
474   *size = (DATA_SIZE * 16 * 39) - *size;
475
476   return IMGTOOLERR_SUCCESS;
477}
478
479static imgtoolerr_t vzdos_diskimage_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
480{
481   imgtoolerr_t ret;
482   imgtool_image *image = imgtool_partition_image(partition);
483   int filesize, track, sector;
484   vzdos_dirent ent;
485   UINT8 buffer[DATA_SIZE + 2];
486     
487   ret = vzdos_get_dirent_fname(image, filename, &ent);
488   if (ret) return ret;
489   
490   filesize = ent.end_address - ent.start_address;
491   track = ent.start_track;
492   sector = ent.start_sector;
493
494   while (filesize > 0) {
495      int towrite;
496
497      ret = vzdos_read_sector_data(image, track, sector, buffer);
498      if (ret) return ret;
499
500      /* detect sectors pointing to themselfs */
501      if ((track == pick_integer_le(buffer, DATA_SIZE, 1)) && (sector == pick_integer_le(buffer, DATA_SIZE + 1, 1)))
502         return IMGTOOLERR_CORRUPTIMAGE;
503
504      /* load next track and sector values */               
505      track  = pick_integer_le(buffer, DATA_SIZE, 1);
506      sector = pick_integer_le(buffer, DATA_SIZE + 1, 1);
507     
508      /* track 0 is invalid */
509      if ((track == 0) && (filesize > DATA_SIZE))
510         return IMGTOOLERR_CORRUPTIMAGE;
511     
512      /* write either DATA_SIZE or the remaining bytes */
513      towrite = filesize > DATA_SIZE ? DATA_SIZE : filesize;
514     
515      if (stream_write(destf, buffer, towrite) != towrite)
516         return IMGTOOLERR_WRITEERROR;
517
518      filesize -= DATA_SIZE;
519   }
520     
521   return IMGTOOLERR_SUCCESS;
522}
523
524/* deletes directory entry, clears trackmap entries and sectors */
525static imgtoolerr_t vzdos_diskimage_deletefile(imgtool_partition *partition, const char *fname)
526{
527   imgtoolerr_t ret;
528   imgtool_image *img = imgtool_partition_image(partition);
529   int index, filesize, track, sector, next_track, next_sector;
530   vzdos_dirent entry, next_entry;
531   UINT8 buffer[DATA_SIZE + 2];
532
533   ret = vzdos_get_dirent_fname(img, fname, &entry);
534   if (ret) return ret;
535
536   ret = floppy_read_sector(imgtool_floppy(img), 0, entry.start_track, sector_order[entry.start_sector], 24, &buffer, DATA_SIZE + 2);
537   if (ret) return ret;
538
539   filesize = entry.end_address - entry.start_address;
540   track    = entry.start_track;
541   sector   = entry.start_sector;
542
543   /* delete directory entry */
544   ret = vzdos_searchentry(img, fname, &index);
545   if (ret) return ret;
546
547   ret = vzdos_get_dirent(img, index + 1, &next_entry);
548
549   if (ret == IMGTOOLERR_FILENOTFOUND) {
550
551      /* we are the last directory entry, just delete it */
552      ret = vzdos_clear_dirent(img, index);
553      if (ret) return ret;
554
555   } else if (ret) {
556
557      /* an error occured */
558      return ret;
559
560   } else {
561
562      ret = vzdos_set_dirent(img, index++, next_entry);
563      if (ret) return ret;
564
565      while ((ret = vzdos_get_dirent(img, index + 1, &next_entry)) != IMGTOOLERR_FILENOTFOUND) {
566         if (ret) return ret;
567         ret = vzdos_set_dirent(img, index++, next_entry);
568         if (ret) return ret;
569      }
570
571      ret = vzdos_clear_dirent(img, index);
572      if (ret) return ret;
573     
574   }
575   
576   /* clear sectors and trackmap entries */
577   while (filesize > 0) {
578   
579      filesize -= DATA_SIZE;
580   
581      /* clear trackmap entry */
582      ret = vzdos_clear_trackmap(img, track, sector);
583      if (ret) return ret;
584
585      /* load next track and sector values */               
586      next_track  = pick_integer_le(buffer, DATA_SIZE, 1);
587      next_sector = pick_integer_le(buffer, DATA_SIZE + 1, 1);
588     
589      /* overwrite sector with default values */
590      ret = vzdos_clear_sector(img, track, sector);
591      if (ret) return ret;
592
593      /* read next sector */
594      track  = next_track;
595      sector = next_sector;
596
597      if (filesize > 0) {
598         ret = floppy_read_sector(imgtool_floppy(img), 0, track, sector_order[sector], 24, &buffer, DATA_SIZE + 2);
599         if (ret) return ret;
600      }     
601           
602   }
603   
604   return IMGTOOLERR_SUCCESS;
605}
606
607static imgtoolerr_t vzdos_writefile(imgtool_partition *partition, int offset, imgtool_stream *sourcef, vzdos_dirent *entry)
608{
609   imgtoolerr_t ret;
610   imgtool_image *img = imgtool_partition_image(partition);
611   int index, track, sector, toread, next_track, next_sector;
612   vzdos_dirent temp_entry;
613   UINT64 filesize = 0, freespace = 0;
614   UINT8 buffer[DATA_SIZE + 2];
615   char filename[9];
616
617   /* is the image writeable? */
618   if (floppy_is_read_only(imgtool_floppy(img)))
619      return IMGTOOLERR_READONLY;
620
621   /* check for already existing filename -> overwrite */
622   strcpy(filename, entry->fname);
623   filename[vzdos_get_fname_len(entry->fname) + 1] = 0x00;
624   ret = vzdos_get_dirent_fname(img, filename, &temp_entry);
625   if (!ret) {
626      /* file already exists, delete it */
627      ret = vzdos_diskimage_deletefile(partition, filename);
628      if (ret) return ret;
629   } else if (ret != IMGTOOLERR_FILENOTFOUND) {
630      /* another error occured, return it */
631      return ret;
632   }
633   
634   ret = stream_seek(sourcef, offset, SEEK_SET);
635   if (ret) return ret;
636
637   /* check if there is enough space */
638   filesize = stream_size(sourcef) - offset;
639
640   ret = vzdos_diskimage_freespace(partition, &freespace);
641   if (ret) return ret;
642
643   if (filesize > freespace)
644      return IMGTOOLERR_NOSPACE;
645   
646   /* get next free track and sector */
647   ret = vzdos_free_trackmap(img, &track, &sector);
648   if (ret) return ret;
649
650   entry->end_address = entry->start_address + (unsigned int) filesize;
651   entry->start_track   = track;
652   entry->start_sector  = sector;
653
654   /* search for next free directory entry */
655   for (index = 0; index < MAX_DIRENTS; index++) {
656      ret = vzdos_get_dirent(img, index, &temp_entry);
657      if (ret == IMGTOOLERR_FILENOTFOUND)
658         break;
659      else if (ret)
660         return (ret);
661   }
662
663   /* write directory entry to disk */
664   ret = vzdos_set_dirent(img, index, *entry);
665   if (ret) return ret;
666
667   next_track  = 0;
668   next_sector = 0;
669   
670   /* write data to disk */
671   while (filesize > 0) {
672   
673      toread = filesize > DATA_SIZE ? DATA_SIZE : filesize;
674      stream_read(sourcef, buffer, toread);
675
676      filesize -= toread;   
677
678      /* mark sector as used */
679      ret = vzdos_set_trackmap(img, track, sector);
680      if (ret) return ret;
681
682      /* get track and sector for next sector */
683      if (filesize > 0) {   
684         ret = vzdos_free_trackmap(img, &next_track, &next_sector);
685         if (ret) return ret;
686      } else {
687         next_track = 0;
688         next_sector = 0;
689      }
690      buffer[DATA_SIZE]     = next_track;
691      buffer[DATA_SIZE + 1] = next_sector;
692
693      /* write sector to disk */
694      ret = vzdos_write_sector_data(img, track, sector, buffer);
695      if (ret) return ret;
696
697      track  = next_track;
698      sector = next_sector;
699   }
700     
701   return IMGTOOLERR_SUCCESS;
702   
703}
704
705/* create a new file or overwrite a file */
706static imgtoolerr_t vzdos_diskimage_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
707{
708   imgtoolerr_t ret;
709   int ftype;
710   vzdos_dirent entry;
711
712   /* TODO: check for leading spaces and strip */
713   if (strlen(filename) > 8 || strlen(filename) < 1)
714      return IMGTOOLERR_BADFILENAME;
715     
716   /* prepare directory entry */
717   ftype = option_resolution_lookup_int(opts, 'T');
718
719   switch (ftype) {
720      case 0:
721         entry.ftype         = 'T';
722         entry.start_address = 31465;
723         break;
724      case 1:
725         entry.ftype         = 'B';
726         entry.start_address = 31465; /* ??? */
727         break;
728      case 2:
729         entry.ftype         = 'D';
730         entry.start_address = 31465; /* ??? */
731         break;
732      default:
733         break;
734   }
735   
736   entry.delimitor = ':';
737   memset(&entry.fname, 0x20, 8); /* pad with spaces */
738   memcpy(&entry.fname, filename, strlen(filename));     
739
740   /* write file to disk */
741   ret = vzdos_writefile(partition, 0, sourcef, &entry);
742   if (ret) return ret;
743   
744   return IMGTOOLERR_SUCCESS;
745}
746
747static imgtoolerr_t vzdos_diskimage_suggesttransfer(imgtool_partition *partition, const char *fname, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
748{
749   imgtoolerr_t ret;
750   imgtool_image *image = imgtool_partition_image(partition);
751   vzdos_dirent entry;
752   
753   if (fname) {
754
755      ret = vzdos_get_dirent_fname(image, fname, &entry);
756      if (ret) return ret;
757     
758      switch (entry.ftype) {
759         case 'B':
760            suggestions[0].viability = SUGGESTION_RECOMMENDED;
761            suggestions[0].filter = filter_vzsnapshot_getinfo;
762            suggestions[0].description = "VZ Snapshot";
763            suggestions[1].viability = SUGGESTION_POSSIBLE;
764            suggestions[1].filter = NULL;
765            suggestions[1].description = "Raw";
766            break;
767         case 'T':
768            suggestions[0].viability = SUGGESTION_RECOMMENDED;
769            suggestions[0].filter = filter_vzsnapshot_getinfo;
770            suggestions[0].description = "VZ Snapshot";
771            suggestions[1].viability = SUGGESTION_POSSIBLE;
772            suggestions[1].filter = NULL;
773            suggestions[1].description = "Raw";           
774            suggestions[2].viability = SUGGESTION_POSSIBLE;
775            suggestions[2].filter = filter_vzbas_getinfo;
776            suggestions[2].description = "Tokenized Basic";
777            break;
778         default:
779            suggestions[0].viability = SUGGESTION_RECOMMENDED;
780            suggestions[0].filter = NULL;
781            suggestions[0].description = "Raw";         
782      }
783     
784   } else {   
785      suggestions[0].viability = SUGGESTION_RECOMMENDED;
786      suggestions[0].filter = NULL;
787      suggestions[0].description = "Raw";
788      suggestions[1].viability = SUGGESTION_POSSIBLE;
789      suggestions[1].filter = filter_vzsnapshot_getinfo;
790      suggestions[1].description = "VZ Snapshot";
791   }
792     
793   return IMGTOOLERR_SUCCESS;
794}
795
796static imgtoolerr_t vzdos_diskimage_create(imgtool_image *img, imgtool_stream *stream, option_resolution *opts)
797{
798   imgtoolerr_t ret;
799   int track, sector;
800
801   for (track = 0; track < 40; track++) {
802      for (sector = 0; sector < 16; sector++) {
803         ret = vzdos_write_formatted_sector(img, track, sector);
804         if (ret) return ret;
805      }
806   }
807   
808   return IMGTOOLERR_SUCCESS;
809}
810
811/*********************************************************************
812   Imgtool vz filter code
813*********************************************************************/
814
815static imgtoolerr_t vzsnapshot_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
816{
817   imgtoolerr_t ret;
818   imgtool_image *image = imgtool_partition_image(partition);
819   vzdos_dirent entry;
820   UINT8 header[24];
821   
822   /* get directory entry from disk */   
823   ret = vzdos_get_dirent_fname(image, filename, &entry);
824   if (ret) return ret;
825
826   /* prepare header */
827   header[0] = 'V';
828   header[1] = 'Z';
829   header[2] = 'F';
830   
831   switch (entry.ftype) {
832      case 'B':
833         header[3] = '1';
834         header[21] = 0xF1;
835         break;
836      case 'T':
837         header[3] = '0';
838         header[21] = 0xF0;   
839         break;
840      default:
841         memset(header, 0x00, 4);
842         header[21] = 0x00;
843   }
844     
845   memset(header + 4, 0x00, 17);
846   memcpy(header + 4, entry.fname, vzdos_get_fname_len(entry.fname) + 1);
847   place_integer_le(header, 22, 2, entry.start_address);
848
849   /* write header to file */
850   stream_write(destf, header, sizeof(header));
851
852   /* write data to file */
853   ret = vzdos_diskimage_readfile(partition, filename, "", destf);
854   if (ret) return ret;
855
856   return IMGTOOLERR_SUCCESS;
857}
858
859static imgtoolerr_t vzsnapshot_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
860{
861   imgtoolerr_t ret;
862   int fnameopt;
863   vzdos_dirent entry;
864   UINT8 header[24];
865
866   /* get header infos from file */
867   stream_read(sourcef, header, sizeof(header));
868   
869   /* prepare directory entry */   
870   entry.ftype         = header[21] == 0xF1 ? 'B' : 'T';
871   entry.delimitor     = ':';
872   entry.start_address = pick_integer_le(header, 22, 2);
873   
874   /* filename from header or directly? */
875   fnameopt = option_resolution_lookup_int(opts, 'F');
876   
877   if (fnameopt == 0) {
878      memcpy(&entry.fname, &header[4], 8);         
879   } else {
880      /* TODO: check for leading spaces and strip */
881      if (strlen(filename) > 8 || strlen(filename) < 1)
882      return IMGTOOLERR_BADFILENAME;
883     
884      memcpy(&entry.fname, filename, strlen(filename) - 3);
885   }
886   
887   /* write file to disk */
888   ret = vzdos_writefile(partition, 24, sourcef, &entry);
889   if (ret) return ret;
890
891   return IMGTOOLERR_SUCCESS;
892}
893
894void filter_vzsnapshot_getinfo(UINT32 state, union filterinfo *info)
895{
896   switch(state)
897   {
898      case FILTINFO_STR_NAME:         info->s = "vzsnapshot"; break;
899      case FILTINFO_STR_HUMANNAME:   info->s = "VZ Snapshot"; break;
900      case FILTINFO_STR_EXTENSION:   info->s = "vz"; break;
901      case FILTINFO_PTR_READFILE:      info->read_file = vzsnapshot_readfile; break;
902      case FILTINFO_PTR_WRITEFILE:   info->write_file = vzsnapshot_writefile; break;
903   }
904}
905
906/*********************************************************************
907   Imgtool module declaration
908*********************************************************************/
909
910OPTION_GUIDE_START(vzdos_writefile_optionguide)
911   OPTION_ENUM_START( 'T', "ftype",  "File type" )
912      OPTION_ENUM(     0, "basic",  "Basic"  )
913      OPTION_ENUM(     1, "binary", "Binary" )
914      OPTION_ENUM(     2, "data",   "Data"   )
915   OPTION_ENUM_END
916   OPTION_ENUM_START( 'F', "fname", "Filename" )
917      OPTION_ENUM(     0, "intern", "Filename from VZ-Header" )
918      OPTION_ENUM(     1, "extern", "Actual filename"         )
919   OPTION_ENUM_END
920OPTION_GUIDE_END
921
922/*
923T   Basic Editor File     
924B   Binary File     
925D   Sequential Access Program Data File     
926F   Quickwrite Document       
927A   Russell Harrison's Edit Ass. File     
928S   Dave Mitchell/Mark Hardwood Edit Ass. File  Start Addr A280H   
929S   Quickwrite/Diskops System File/Label       Except Above   
930W   Edit Ass. with Diskops File   Start           Addr A813H   
931W   E & F Word Pro with Patch 3.3 File           End Addr D000H   
932W   Russell Harrison Word Pro File              Except above two   
933*/
934
935void vzdos_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
936{
937   switch(state)
938   {
939      /* --- the following bits of info are returned as 64-bit signed integers --- */
940      case IMGTOOLINFO_INT_PREFER_UCASE:               info->i = 1; break;
941      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(vz_iterator); break;
942
943      /* --- the following bits of info are returned as NULL-terminated strings --- */
944      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "vzdos"); break;
945      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "VZ-DOS format"); break;
946      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
947      case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC:            strcpy(info->s = imgtool_temp_str(), "T[0]-2;F[0]-1"); break;
948      case IMGTOOLINFO_STR_EOLN:                     info->s = NULL; break;
949
950      /* --- the following bits of info are returned as pointers to data or functions --- */
951      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
952      case IMGTOOLINFO_PTR_OPEN:                     info->open = NULL; break;
953      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = vzdos_diskimage_beginenum; break;
954      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = vzdos_diskimage_nextenum; break;
955      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = vzdos_diskimage_freespace; break;
956      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = vzdos_diskimage_readfile; break;
957      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = vzdos_diskimage_writefile; break;
958      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = vzdos_diskimage_deletefile; break;
959      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = vzdos_diskimage_create; break;
960      case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE:         info->writefile_optguide = vzdos_writefile_optionguide; break;
961      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = vzdos_diskimage_suggesttransfer; break;
962      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_vz; break;
963   }
964}
src/mess/tools/imgtool/modules/prodos.c
r0r1340
1/****************************************************************************
2
3   prodos.c
4
5   Apple II ProDOS disk images
6
7*****************************************************************************
8
9  Notes:
10  - ProDOS disks are split into 512 byte blocks.
11
12  ProDOS directory structure:
13
14  Offset  Length  Description
15  ------  ------  -----------
16       0       2  ???
17       2       2  Next block (0 if end)
18       4      39  Directory Entry
19      43      39  Directory Entry
20                  ...
21     472      39  Directory Entry
22     511       1  ???
23
24
25  ProDOS directory entry structure:
26
27  Offset  Length  Description
28  ------  ------  -----------
29       0       1  Storage type (bits 7-4)
30                     10 - Seedling File (1 block)
31                 20 - Sapling File (2-256 blocks)
32                 30 - Tree File (257-32768 blocks)
33                 40 - Pascal Areas on ProFile HDs (???)
34                 50 - GS/OS Extended File (data and rsrc fork)
35                 E0 - Subdirectory Header
36                  F0 - Volume Header
37       1      15  File name (NUL padded)
38      16       1  File type
39      17       2  Key pointer
40      19       2  Blocks used
41      21       3  File size
42      24       4  Creation date
43      28       1  ProDOS version that created the file
44      29       1  Minimum ProDOS version needed to read the file
45      30       1  Access byte
46      31       2  Auxilary file type
47      33       4  Last modified date
48      37       2  Header pointer
49
50
51  In "seedling files", the key pointer points to a single block that is the
52  whole file.  In "sapling files", the key pointer points to an index block
53  that contains 256 2-byte index pointers that point to the actual blocks of
54  the files.  These 2-byte values are not contiguous; the low order byte is
55  in the first half of the block, and the high order byte is in the second
56  half of the block.  In "tree files", the key pointer points to an index
57  block of index blocks.
58
59  ProDOS dates are 32-bit little endian values
60
61   bits  0- 4   Day
62   bits  5- 8   Month (0-11)
63   bits  9-15   Year (0-49 is 2000-2049, 50-99 is 1950-1999)
64   bits 16-21   Minute
65   bits 24-28   Hour
66
67
68  ProDOS directory and volume headers have this information:
69
70  Offset  Length  Description
71  ------  ------  -----------
72      31       1  Length of the entry; generally is 39
73     32       1  Number of entries per block; generally is 13
74     33       2  Active entry count in directory
75     35       2  Volume bitmap block number
76     37       2  Total blocks on volume
77
78  GS/OS Extended Files (storage type $5) point to an extended key block that
79  contains information about the two forks.  The first half of the extended
80  key block contains info about the data form, and the second half the
81  resource fork.  Both sides have the following format:
82
83  Offset  Length  Description
84  ------  ------  -----------
85       0       1  Storage type (bits 3-0, unlike the directory entry)
86      1       2  Key pointer
87      3       2  Blocks used
88      5       3  File size
89      8       1  Size of secondary info #1 (must be 18 to be valid)
90      9       1  Secondary info #1 type (1=FInfo 2=xFInfo)
91     10      16  FInfo or xFInfo
92     26       1  Size of secondary info #2 (must be 18 to be valid)
93     27       1  Secondary info #2 type (1=FInfo 2=xFInfo)
94     28      16  FInfo or xFInfo
95
96  FInfo format:
97
98  Offset  Length  Description
99  ------  ------  -----------
100       0       4  File type
101      4       4  File creator
102      8       2  Finder flags
103      10       2  X Coordinate
104     12       2  Y Coordinate
105     14       2  Finder folder
106
107  xFInfo format:
108
109  Offset  Length  Description
110  ------  ------  -----------
111       0       2  Icon ID
112      2       6  Reserved
113      8       1  Script Code
114      9       1  Extended flags
115      10       2  Comment ID
116     12       4  Put Away Directory
117
118
119  For more info, consult ProDOS technical note #25
120   (http://web.pdx.edu/~heiss/technotes/pdos/tn.pdos.25.html)
121
122*****************************************************************************/
123
124#include "imgtool.h"
125#include "formats/ap2_dsk.h"
126#include "formats/ap_dsk35.h"
127#include "iflopimg.h"
128#include "macutil.h"
129
130#define   ROOTDIR_BLOCK         2
131#define BLOCK_SIZE            512
132
133typedef struct _prodos_diskinfo prodos_diskinfo;
134struct _prodos_diskinfo
135{
136   imgtoolerr_t (*load_block)(imgtool_image *image, int block, void *buffer);
137   imgtoolerr_t (*save_block)(imgtool_image *image, int block, const void *buffer);
138   UINT8 dirent_size;
139   UINT8 dirents_per_block;
140   UINT16 volume_bitmap_block;
141   UINT16 total_blocks;
142};
143
144typedef struct _prodos_direnum prodos_direnum;
145struct _prodos_direnum
146{
147   UINT32 block;
148   UINT32 index;
149   UINT8 block_data[BLOCK_SIZE];
150};
151
152typedef struct _prodos_dirent prodos_dirent;
153struct _prodos_dirent
154{
155   char filename[16];
156   UINT8 storage_type;
157   UINT16 extkey_pointer;
158   UINT16 key_pointer[2];
159   UINT32 filesize[2];
160   int depth[2];
161   UINT32 lastmodified_time;
162   UINT32 creation_time;
163
164   /* FInfo */
165   UINT32 file_type;
166   UINT32 file_creator;
167   UINT16 finder_flags;
168   UINT16 coord_x;
169   UINT16 coord_y;
170   UINT16 finder_folder;
171
172   /* xFInfo */
173   UINT16 icon_id;
174   UINT8 script_code;
175   UINT8 extended_flags;
176   UINT16 comment_id;
177   UINT32 putaway_directory;
178};
179
180typedef enum
181{
182   CREATE_NONE,
183   CREATE_FILE,
184   CREATE_DIR
185} creation_policy_t;
186
187
188
189static time_t prodos_crack_time(UINT32 prodos_time)
190{
191   struct tm t;
192   time_t now;
193
194   time(&now);
195   t = *localtime(&now);
196
197   t.tm_sec   = 0;
198   t.tm_min   = (prodos_time >> 16) & 0x3F;
199   t.tm_hour   = (prodos_time >> 24) & 0x1F;
200   t.tm_mday   = (prodos_time >>  0) & 0x1F;
201   t.tm_mon   = (prodos_time >>  5) & 0x0F;
202   t.tm_year   = (prodos_time >>  9) & 0x7F;
203
204   if (t.tm_year <= 49)
205      t.tm_year += 100;
206   return mktime(&t);
207}
208
209
210
211static UINT32 prodos_setup_time(time_t ansi_time)
212{
213   struct tm t;
214   UINT32 result = 0;
215
216   t = *localtime(&ansi_time);
217   if ((t.tm_year >= 100) && (t.tm_year <= 149))
218      t.tm_year -= 100;
219
220   result |= (((UINT32) t.tm_min)   & 0x003F) << 16;
221   result |= (((UINT32) t.tm_hour)   & 0x001F) << 24;
222   result |= (((UINT32) t.tm_mday)   & 0x001F) <<  0;
223   result |= (((UINT32) t.tm_mon)   & 0x000F) <<  5;
224   result |= (((UINT32) t.tm_year)   & 0x007F) <<  9;
225   return result;
226}
227
228
229
230static UINT32 prodos_time_now(void)
231{
232   time_t now;
233   time(&now);
234   return prodos_setup_time(now);
235}
236
237
238
239static int is_file_storagetype(UINT8 storage_type)
240{
241   return ((storage_type >= 0x10) && (storage_type <= 0x3F))
242      || ((storage_type >= 0x50) && (storage_type <= 0x5F));
243}
244
245
246
247static int is_normalfile_storagetype(UINT8 storage_type)
248{
249   return ((storage_type >= 0x10) && (storage_type <= 0x3F));
250}
251
252
253
254static int is_extendedfile_storagetype(UINT8 storage_type)
255{
256   return ((storage_type >= 0x50) && (storage_type <= 0x5F));
257}
258
259
260
261static int is_dir_storagetype(UINT8 storage_type)
262{
263   return (storage_type >= 0xE0) && (storage_type <= 0xEF);
264}
265
266
267
268static prodos_diskinfo *get_prodos_info(imgtool_image *image)
269{
270   prodos_diskinfo *info;
271   info = (prodos_diskinfo *) imgtool_floppy_extrabytes(image);
272   return info;
273}
274
275
276
277/* ----------------------------------------------------------------------- */
278
279static void prodos_find_block_525(imgtool_image *image, int block,
280   UINT32 *track, UINT32 *head, UINT32 *sector1, UINT32 *sector2)
281{
282   static const UINT8 skewing[] =
283   {
284      0x00, 0x02, 0x04, 0x06, 0x08, 0x0A, 0x0C, 0x0E,
285      0x01, 0x03, 0x05, 0x07, 0x09, 0x0B, 0x0D, 0x0F
286   };
287
288   block *= 2;
289
290   *track = block / APPLE2_SECTOR_COUNT;
291   *head = 0;
292   *sector1 = skewing[block % APPLE2_SECTOR_COUNT + 0];
293   *sector2 = skewing[block % APPLE2_SECTOR_COUNT + 1];
294}
295
296
297
298static imgtoolerr_t prodos_load_block_525(imgtool_image *image,
299   int block, void *buffer)
300{
301   floperr_t ferr;
302   UINT32 track, head, sector1, sector2;
303
304   prodos_find_block_525(image, block, &track, &head, &sector1, &sector2);
305
306   /* read first sector */
307   ferr = floppy_read_sector(imgtool_floppy(image), head, track,
308      sector1, 0, ((UINT8 *) buffer) + 0, 256);
309   if (ferr)
310      return imgtool_floppy_error(ferr);
311
312   /* read second sector */
313   ferr = floppy_read_sector(imgtool_floppy(image), head, track,
314      sector2, 0, ((UINT8 *) buffer) + 256, 256);
315   if (ferr)
316      return imgtool_floppy_error(ferr);
317
318   return IMGTOOLERR_SUCCESS;
319}
320
321
322
323static imgtoolerr_t prodos_save_block_525(imgtool_image *image,
324   int block, const void *buffer)
325{
326   floperr_t ferr;
327   UINT32 track, head, sector1, sector2;
328
329   prodos_find_block_525(image, block, &track, &head, &sector1, &sector2);
330
331   /* read first sector */
332   ferr = floppy_write_sector(imgtool_floppy(image), head, track,
333      sector1, 0, ((const UINT8 *) buffer) + 0, 256);
334   if (ferr)
335      return imgtool_floppy_error(ferr);
336
337   /* read second sector */
338   ferr = floppy_write_sector(imgtool_floppy(image), head, track,
339      sector2, 0, ((const UINT8 *) buffer) + 256, 256);
340   if (ferr)
341      return imgtool_floppy_error(ferr);
342
343   return IMGTOOLERR_SUCCESS;
344}
345
346
347
348static void prodos_setprocs_525(imgtool_image *image)
349{
350   prodos_diskinfo *info;
351   info = get_prodos_info(image);
352   info->load_block = prodos_load_block_525;
353   info->save_block = prodos_save_block_525;
354}
355
356
357
358/* ----------------------------------------------------------------------- */
359
360static imgtoolerr_t prodos_find_block_35(imgtool_image *image, int block,
361   UINT32 *track, UINT32 *head, UINT32 *sector)
362{
363   int sides = 2;
364
365   *track = 0;
366   while(block >= (apple35_sectors_per_track(imgtool_floppy(image), *track) * sides))
367   {
368      block -= (apple35_sectors_per_track(imgtool_floppy(image), (*track)++) * sides);
369      if (*track >= 80)
370         return IMGTOOLERR_SEEKERROR;
371   }
372
373   *head = block / apple35_sectors_per_track(imgtool_floppy(image), *track);
374   *sector = block % apple35_sectors_per_track(imgtool_floppy(image), *track);
375   return IMGTOOLERR_SUCCESS;
376}
377
378
379
380static imgtoolerr_t prodos_load_block_35(imgtool_image *image,
381   int block, void *buffer)
382{
383   imgtoolerr_t err;
384   floperr_t ferr;
385   UINT32 track, head, sector;
386
387   err = prodos_find_block_35(image, block, &track, &head, &sector);
388   if (err)
389      return err;
390
391   ferr = floppy_read_sector(imgtool_floppy(image), head, track, sector, 0, buffer, 512);
392   if (ferr)
393      return imgtool_floppy_error(ferr);
394
395   return IMGTOOLERR_SUCCESS;
396}
397
398
399
400static imgtoolerr_t prodos_save_block_35(imgtool_image *image,
401   int block, const void *buffer)
402{
403   imgtoolerr_t err;
404   floperr_t ferr;
405   UINT32 track, head, sector;
406
407   err = prodos_find_block_35(image, block, &track, &head, &sector);
408   if (err)
409      return err;
410
411   ferr = floppy_write_sector(imgtool_floppy(image), head, track, sector, 0, buffer, 512);
412   if (ferr)
413      return imgtool_floppy_error(ferr);
414
415   return IMGTOOLERR_SUCCESS;
416}
417
418
419
420static void prodos_setprocs_35(imgtool_image *image)
421{
422   prodos_diskinfo *info;
423   info = get_prodos_info(image);
424   info->load_block = prodos_load_block_35;
425   info->save_block = prodos_save_block_35;
426}
427
428
429
430/* ----------------------------------------------------------------------- */
431
432static imgtoolerr_t prodos_load_block(imgtool_image *image,
433   int block, void *buffer)
434{
435   prodos_diskinfo *diskinfo;
436   diskinfo = get_prodos_info(image);
437   return diskinfo->load_block(image, block, buffer);
438}
439
440
441
442static imgtoolerr_t prodos_save_block(imgtool_image *image,
443   int block, const void *buffer)
444{
445   prodos_diskinfo *diskinfo;
446   diskinfo = get_prodos_info(image);
447   return diskinfo->save_block(image, block, buffer);
448}
449
450
451
452static imgtoolerr_t prodos_clear_block(imgtool_image *image, int block)
453{
454   UINT8 buffer[BLOCK_SIZE];
455   memset(buffer, 0, sizeof(buffer));
456   return prodos_save_block(image, block, buffer);
457}
458
459
460
461/* ----------------------------------------------------------------------- */
462
463static imgtoolerr_t prodos_diskimage_open(imgtool_image *image)
464{
465   imgtoolerr_t err;
466   UINT8 buffer[BLOCK_SIZE];
467   prodos_diskinfo *di;
468   const UINT8 *ent;
469
470   di = get_prodos_info(image);
471
472   /* specify defaults */
473   di->dirent_size = 39;
474   di->dirents_per_block = 13;
475
476   /* load the first block, hoping that the volume header is first */
477   err = prodos_load_block(image, ROOTDIR_BLOCK, buffer);
478   if (err)
479      return err;
480
481   ent = &buffer[4];
482
483   /* did we find the volume header? */
484   if ((ent[0] & 0xF0) == 0xF0)
485   {
486      di->dirent_size         = pick_integer_le(ent, 31, 1);
487      di->dirents_per_block   = pick_integer_le(ent, 32, 1);
488      di->volume_bitmap_block   = pick_integer_le(ent, 35, 2);
489      di->total_blocks      = pick_integer_le(ent, 37, 2);
490   }
491
492   /* sanity check these values */
493   if (di->dirent_size < 39)
494      return IMGTOOLERR_CORRUPTIMAGE;
495   if (di->dirents_per_block * di->dirent_size >= BLOCK_SIZE)
496      return IMGTOOLERR_CORRUPTIMAGE;
497   if (di->volume_bitmap_block >= di->total_blocks)
498      return IMGTOOLERR_CORRUPTIMAGE;
499
500   return IMGTOOLERR_SUCCESS;
501}
502
503
504
505static imgtoolerr_t prodos_diskimage_open_525(imgtool_image *image, imgtool_stream *stream)
506{
507   prodos_setprocs_525(image);
508   return prodos_diskimage_open(image);
509}
510
511
512
513static imgtoolerr_t prodos_diskimage_open_35(imgtool_image *image, imgtool_stream *stream)
514{
515   prodos_setprocs_35(image);
516   return prodos_diskimage_open(image);
517}
518
519
520
521/* ----------------------------------------------------------------------- */
522
523static imgtoolerr_t prodos_load_volume_bitmap(imgtool_image *image, UINT8 **bitmap)
524{
525   imgtoolerr_t err;
526   prodos_diskinfo *di;
527   UINT8 *alloc_bitmap;
528   UINT32 bitmap_blocks, i;
529
530   di = get_prodos_info(image);
531
532   bitmap_blocks = (di->total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
533   alloc_bitmap = malloc(bitmap_blocks * BLOCK_SIZE);
534   if (!alloc_bitmap)
535   {
536      err = IMGTOOLERR_OUTOFMEMORY;
537      goto done;
538   }
539
540   for (i = 0; i < bitmap_blocks; i++)
541   {
542      err = prodos_load_block(image, di->volume_bitmap_block + i,
543         &alloc_bitmap[i * BLOCK_SIZE]);
544      if (err)
545         goto done;
546   }
547
548   err = IMGTOOLERR_SUCCESS;
549
550done:
551   if (err && alloc_bitmap)
552   {
553      free(alloc_bitmap);
554      alloc_bitmap = NULL;
555   }
556   *bitmap = alloc_bitmap;
557   return err;
558}
559
560
561
562static imgtoolerr_t prodos_save_volume_bitmap(imgtool_image *image, const UINT8 *bitmap)
563{
564   imgtoolerr_t err;
565   prodos_diskinfo *di;
566   UINT32 bitmap_blocks, i;
567
568   di = get_prodos_info(image);
569
570   bitmap_blocks = (di->total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
571
572   for (i = 0; i < bitmap_blocks; i++)
573   {
574      err = prodos_save_block(image, di->volume_bitmap_block + i,
575         &bitmap[i * BLOCK_SIZE]);
576      if (err)
577         return err;
578   }
579   return IMGTOOLERR_SUCCESS;
580}
581
582
583
584static void prodos_set_volume_bitmap_bit(UINT8 *buffer, UINT16 block, int value)
585{
586   UINT8 mask;
587   buffer += block / 8;
588   mask = 1 << (7 - (block % 8));
589   if (value)
590      *buffer |= mask;
591   else
592      *buffer &= ~mask;
593}
594
595
596
597static int prodos_get_volume_bitmap_bit(const UINT8 *buffer, UINT16 block)
598{
599   UINT8 mask;
600   buffer += block / 8;
601   mask = 1 << (7 - (block % 8));
602   return (*buffer & mask) ? 1 : 0;
603}
604
605
606
607static imgtoolerr_t prodos_alloc_block(imgtool_image *image, UINT8 *bitmap,
608   UINT16 *block)
609{
610   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
611   prodos_diskinfo *di;
612   UINT16 bitmap_blocks, i;
613   UINT8 *alloc_bitmap = NULL;
614
615   di = get_prodos_info(image);
616   *block = 0;
617   bitmap_blocks = (di->total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
618
619   if (!bitmap)
620   {
621      err = prodos_load_volume_bitmap(image, &alloc_bitmap);
622      if (err)
623         goto done;
624      bitmap = alloc_bitmap;
625   }
626
627   for (i = (di->volume_bitmap_block + bitmap_blocks); i < di->total_blocks; i++)
628   {
629      if (!prodos_get_volume_bitmap_bit(bitmap, i))
630      {
631         prodos_set_volume_bitmap_bit(bitmap, i, 1);
632         *block = i;
633         break;
634      }
635   }
636
637   if (*block > 0)
638   {
639      if (alloc_bitmap)
640      {
641         err = prodos_save_volume_bitmap(image, bitmap);
642         if (err)
643            goto done;
644      }
645   }
646   else
647   {
648      err = IMGTOOLERR_NOSPACE;
649   }
650
651done:
652   if (err)
653      *block = 0;
654   if (alloc_bitmap)
655      free(alloc_bitmap);
656   return err;
657}
658
659
660
661/* ----------------------------------------------------------------------- */
662
663static imgtoolerr_t prodos_diskimage_create(imgtool_image *image, option_resolution *opts)
664{
665   imgtoolerr_t err;
666   UINT32 heads, tracks, sectors, sector_bytes;
667   UINT32 dirent_size, volume_bitmap_block, i;
668   UINT32 volume_bitmap_block_count, total_blocks;
669   UINT8 buffer[BLOCK_SIZE];
670
671   heads = option_resolution_lookup_int(opts, 'H');
672   tracks = option_resolution_lookup_int(opts, 'T');
673   sectors = option_resolution_lookup_int(opts, 'S');
674   sector_bytes = option_resolution_lookup_int(opts, 'L');
675
676   dirent_size = 39;
677   volume_bitmap_block = 6;
678   total_blocks = tracks * heads * sectors * sector_bytes / BLOCK_SIZE;
679   volume_bitmap_block_count = (total_blocks + (BLOCK_SIZE * 8) - 1) / (BLOCK_SIZE * 8);
680
681   /* prepare initial dir block */
682   memset(buffer, 0, sizeof(buffer));
683   place_integer_le(buffer, 4 +  0, 1, 0xF0);
684   place_integer_le(buffer, 4 + 31, 1, dirent_size);
685   place_integer_le(buffer, 4 + 32, 1, BLOCK_SIZE / dirent_size);
686   place_integer_le(buffer, 4 + 35, 2, volume_bitmap_block);
687   place_integer_le(buffer, 4 + 37, 2, total_blocks);
688
689   err = prodos_save_block(image, ROOTDIR_BLOCK, buffer);
690   if (err)
691      return err;
692
693   /* setup volume bitmap */
694   memset(buffer, 0, sizeof(buffer));
695   for (i = 0; i < (volume_bitmap_block + volume_bitmap_block_count); i++)
696      prodos_set_volume_bitmap_bit(buffer, i, 1);
697   prodos_save_block(image, volume_bitmap_block, buffer);
698
699   /* and finally open the image */
700   return prodos_diskimage_open(image);
701}
702
703
704
705static imgtoolerr_t prodos_diskimage_create_525(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
706{
707   prodos_setprocs_525(image);
708   return prodos_diskimage_create(image, opts);
709}
710
711
712
713static imgtoolerr_t prodos_diskimage_create_35(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
714{
715   prodos_setprocs_35(image);
716   return prodos_diskimage_create(image, opts);
717}
718
719
720
721/* ----------------------------------------------------------------------- */
722
723static imgtoolerr_t prodos_enum_seek(imgtool_image *image,
724   prodos_direnum *appleenum, UINT32 block, UINT32 index)
725{
726   imgtoolerr_t err;
727   UINT8 buffer[BLOCK_SIZE];
728
729   if (appleenum->block != block)
730   {
731      if (block != 0)
732      {
733         err = prodos_load_block(image, block, buffer);
734         if (err)
735            return err;
736         memcpy(appleenum->block_data, buffer, sizeof(buffer));
737      }
738      appleenum->block = block;
739   }
740
741   appleenum->index = index;
742   return IMGTOOLERR_SUCCESS;
743}
744
745
746
747static UINT8 *next_info_block(UINT8 *buffer, size_t *position)
748{
749   size_t side = *position & 0x100;
750   size_t subpos = *position & 0x0FF;
751   UINT8 *result;
752
753   if (subpos < 8)
754   {
755      subpos = 8;
756      *position = side + subpos;
757   }
758
759   while((buffer[side + subpos] == 0x00) || (subpos + buffer[side + subpos] > 0x100))
760   {
761      if (side)
762         return NULL;
763     
764      side = 0x100;
765      subpos = 8;
766   }
767
768   result = &buffer[side + subpos];
769   subpos += *result;
770   *position = side + subpos;
771   return result;
772}
773
774
775
776static UINT8 *alloc_info_block(UINT8 *buffer, size_t block_size, UINT8 block_type)
777{
778   size_t position = 0;
779   size_t side;
780   size_t subpos;
781   UINT8 *result;
782
783   while(next_info_block(buffer, &position))
784      ;
785
786   side = position & 0x100;
787   subpos = position & 0x0FF;
788
789   if ((subpos + block_size) > 0x100)
790      return NULL;
791
792   result = &buffer[side + subpos];
793   *(result++) = (UINT8) block_size;
794   *(result++) = block_type;
795   memset(result, 0, block_size - 2);
796   return result;
797}
798
799
800
801static imgtoolerr_t prodos_get_next_dirent(imgtool_image *image,
802   prodos_direnum *appleenum, prodos_dirent *ent)
803{
804   imgtoolerr_t err;
805   prodos_diskinfo *di;
806   size_t finfo_offset;
807   UINT32 next_block, next_index;
808   UINT32 offset;
809   UINT8 buffer[BLOCK_SIZE];
810   const UINT8 *info_ptr;
811   mac_fork_t fork_num;
812
813   di = get_prodos_info(image);
814   memset(ent, 0, sizeof(*ent));
815
816   /* have we hit the end of the file? */
817   if (appleenum->block == 0)
818      return IMGTOOLERR_SUCCESS;
819
820   /* populate the resulting dirent */
821   offset = appleenum->index * di->dirent_size + 4;
822   ent->storage_type = appleenum->block_data[offset + 0];
823   memcpy(ent->filename, &appleenum->block_data[offset + 1], 15);
824   ent->filename[15] = '\0';
825   ent->creation_time      = pick_integer_le(appleenum->block_data, offset + 24, 4);
826   ent->lastmodified_time   = pick_integer_le(appleenum->block_data, offset + 33, 4);
827   ent->file_type = 0x3F3F3F3F;
828   ent->file_creator = 0x3F3F3F3F;
829   ent->finder_flags  = 0;
830   ent->coord_x = 0;
831   ent->coord_y = 0;
832   ent->finder_folder = 0;
833   ent->icon_id = 0;
834   ent->script_code = 0;
835   ent->extended_flags = 0;
836   ent->comment_id = 0;
837   ent->putaway_directory = 0;
838
839   if (is_extendedfile_storagetype(ent->storage_type))
840   {
841      /* this is a ProDOS extended file; we need to get the extended info
842       * block */
843      ent->extkey_pointer   = pick_integer_le(appleenum->block_data, offset + 17, 2);
844
845      err = prodos_load_block(image, ent->extkey_pointer, buffer);
846      if (err)
847         return err;
848
849      for (fork_num = 0; fork_num <= 1; fork_num++)
850      {
851         ent->key_pointer[fork_num]   = pick_integer_le(buffer, 1 + (fork_num * 256), 2);
852         ent->filesize[fork_num]      = pick_integer_le(buffer, 5 + (fork_num * 256), 3);
853         ent->depth[fork_num]      = buffer[fork_num * 256] & 0x0F;
854      }
855
856      finfo_offset = 0;
857      while((info_ptr = next_info_block(buffer, &finfo_offset)) != NULL)
858      {
859         if (*(info_ptr++) == 18)
860         {
861            switch(*(info_ptr++))
862            {
863               case 1:   /* FInfo */
864                  ent->file_type     = pick_integer_be(info_ptr,  0, 4);
865                  ent->file_creator  = pick_integer_be(info_ptr,  4, 4);
866                  ent->finder_flags  = pick_integer_be(info_ptr,  8, 2);
867                  ent->coord_x       = pick_integer_be(info_ptr, 10, 2);
868                  ent->coord_y       = pick_integer_be(info_ptr, 12, 2);
869                  ent->finder_folder = pick_integer_be(info_ptr, 14, 4);
870                  break;
871
872               case 2:   /* xFInfo */
873                  ent->icon_id           = pick_integer_be(info_ptr,  0, 2);
874                  ent->script_code       = pick_integer_be(info_ptr,  8, 1);
875                  ent->extended_flags    = pick_integer_be(info_ptr,  9, 1);
876                  ent->comment_id        = pick_integer_be(info_ptr, 10, 2);
877                  ent->putaway_directory = pick_integer_be(info_ptr, 12, 4);
878                  break;
879            }
880         }
881      }
882   }
883   else
884   {
885      /* normal ProDOS files have all of the info right here */
886      ent->key_pointer[0]   = pick_integer_le(appleenum->block_data, offset + 17, 2);
887      ent->filesize[0]   = pick_integer_le(appleenum->block_data, offset + 21, 3);
888      ent->depth[0]      = ent->storage_type >> 4;
889   }
890
891   /* identify next entry */
892   next_block = appleenum->block;
893   next_index = appleenum->index + 1;
894   if (next_index >= di->dirents_per_block)
895   {
896      next_block = pick_integer_le(appleenum->block_data, 2, 2);
897      next_index = 0;
898   }
899
900   /* seek next block */
901   err = prodos_enum_seek(image, appleenum, next_block, next_index);
902   if (err)
903      return err;
904
905   return IMGTOOLERR_SUCCESS;
906}
907
908
909
910/* changes a normal file to a ProDOS extended file */
911static imgtoolerr_t prodos_promote_file(imgtool_image *image, UINT8 *bitmap, prodos_dirent *ent)
912{
913   imgtoolerr_t err;
914   UINT16 new_block;
915   UINT8 buffer[BLOCK_SIZE];
916
917   assert(is_normalfile_storagetype(ent->storage_type));
918
919   err = prodos_alloc_block(image, bitmap, &new_block);
920   if (err)
921      return err;
922
923   /* create raw extended info block */
924   memset(buffer, 0, sizeof(buffer));
925   err = prodos_save_block(image, new_block, buffer);
926   if (err)
927      return err;
928
929   ent->storage_type = (ent->storage_type & 0x0F) | 0x50;
930   ent->extkey_pointer = new_block;
931   return IMGTOOLERR_SUCCESS;
932}
933
934
935
936static imgtoolerr_t prodos_put_dirent(imgtool_image *image,
937   prodos_direnum *appleenum, prodos_dirent *ent)
938{
939   imgtoolerr_t err;
940   prodos_diskinfo *di;
941   UINT32 offset;
942   size_t finfo_offset;
943   UINT8 buffer[BLOCK_SIZE];
944   mac_fork_t fork_num;
945   int needs_finfo = FALSE;
946   int needs_xfinfo = FALSE;
947   UINT8 *info_ptr;
948   UINT8 *finfo;
949   UINT8 *xfinfo;
950
951   di = get_prodos_info(image);
952   offset = appleenum->index * di->dirent_size + 4;
953
954   /* determine whether we need FInfo and/or xFInfo */
955   if (is_normalfile_storagetype(ent->storage_type))
956   {
957      needs_finfo = (ent->file_type != 0x3F3F3F3F) ||
958         (ent->file_creator != 0x3F3F3F3F) ||
959         (ent->finder_flags != 0) ||
960         (ent->coord_x != 0) ||
961         (ent->coord_y != 0) ||
962         (ent->finder_folder != 0);
963
964      needs_xfinfo = (ent->icon_id != 0) ||
965         (ent->script_code != 0) ||
966         (ent->extended_flags != 0) ||
967         (ent->comment_id != 0) ||
968         (ent->putaway_directory != 0);
969   }
970
971   /* do we need to promote this file to an extended file? */
972   if (!is_extendedfile_storagetype(ent->storage_type)
973      && (needs_finfo || needs_xfinfo))
974   {
975      err = prodos_promote_file(image, NULL, ent);
976      if (err)
977         return err;
978   }
979
980   /* write out the storage type, filename, creation and lastmodified times */
981   appleenum->block_data[offset + 0] = ent->storage_type;
982   memcpy(&appleenum->block_data[offset + 1], ent->filename, 15);
983   place_integer_le(appleenum->block_data, offset + 24, 4, ent->creation_time);
984   place_integer_le(appleenum->block_data, offset + 33, 4, ent->lastmodified_time);
985
986   if (is_extendedfile_storagetype(ent->storage_type))
987   {
988      /* ProDOS extended file */
989      err = prodos_load_block(image, ent->extkey_pointer, buffer);
990      if (err)
991         return err;
992
993      finfo = NULL;
994      xfinfo = NULL;
995
996      for (fork_num = 0; fork_num <= 1; fork_num++)
997      {
998         place_integer_le(buffer, 1 + (fork_num * 256), 2, ent->key_pointer[fork_num]);
999         place_integer_le(buffer, 5 + (fork_num * 256), 3, ent->filesize[fork_num]);
1000         buffer[fork_num * 256] = ent->depth[fork_num];
1001      }
1002
1003      finfo_offset = 0;
1004      while((info_ptr = next_info_block(buffer, &finfo_offset)) != NULL)
1005      {
1006         if (*(info_ptr++) == 18)
1007         {
1008            switch(*(info_ptr++))
1009            {
1010               case 1:   /* FInfo */
1011                  finfo = info_ptr;
1012                  break;
1013
1014               case 2:   /* xFInfo */
1015                  xfinfo = info_ptr;
1016                  break;
1017            }
1018         }
1019      }
1020
1021      /* allocate the finfo and/or xinfo blocks, if we need them */
1022      if (needs_finfo && !finfo)
1023         finfo = alloc_info_block(buffer, 18, 1);
1024      if (needs_xfinfo && !xfinfo)
1025         xfinfo = alloc_info_block(buffer, 18, 2);
1026
1027      if (finfo)
1028      {
1029         place_integer_be(finfo,  0, 4, ent->file_type);
1030         place_integer_be(finfo,  4, 4, ent->file_creator);
1031         place_integer_be(finfo,  8, 2, ent->finder_flags);
1032         place_integer_be(finfo, 10, 2, ent->coord_x);
1033         place_integer_be(finfo, 12, 2, ent->coord_y);
1034         place_integer_be(finfo, 14, 4, ent->finder_folder);
1035      }
1036
1037      if (xfinfo)
1038      {
1039         place_integer_be(xfinfo,  0, 2, ent->icon_id);
1040         place_integer_be(xfinfo,  8, 1, ent->script_code);
1041         place_integer_be(xfinfo,  9, 1, ent->extended_flags);
1042         place_integer_be(xfinfo, 10, 2, ent->comment_id);
1043         place_integer_be(xfinfo, 12, 4, ent->putaway_directory);
1044      }
1045
1046      err = prodos_save_block(image, ent->extkey_pointer, buffer);
1047      if (err)
1048         return err;
1049
1050      place_integer_le(appleenum->block_data, offset + 17, 2, ent->extkey_pointer);
1051      place_integer_le(appleenum->block_data, offset + 21, 3, BLOCK_SIZE);
1052   }
1053   else
1054   {
1055      /* normal file */
1056      place_integer_le(appleenum->block_data, offset + 17, 2, ent->key_pointer[0]);
1057      place_integer_le(appleenum->block_data, offset + 21, 3, ent->filesize[0]);
1058   }
1059
1060   err = prodos_save_block(image, appleenum->block, appleenum->block_data);
1061   if (err)
1062      return err;
1063
1064   return IMGTOOLERR_SUCCESS;
1065}
1066
1067
1068
1069static imgtoolerr_t prodos_lookup_path(imgtool_image *image, const char *path,
1070   creation_policy_t create, prodos_direnum *direnum, prodos_dirent *ent)
1071{
1072   imgtoolerr_t err;
1073   prodos_direnum my_direnum;
1074   UINT32 block = ROOTDIR_BLOCK;
1075   const char *old_path;
1076   UINT16 this_block;
1077   UINT32 this_index;
1078   UINT16 free_block = 0;
1079   UINT32 free_index = 0;
1080   UINT16 new_file_block;
1081   UINT8 buffer[BLOCK_SIZE];
1082
1083   if (!direnum)
1084      direnum = &my_direnum;
1085
1086   while(*path)
1087   {
1088      memset(direnum, 0, sizeof(*direnum));
1089      err = prodos_enum_seek(image, direnum, block, 0);
1090      if (err)
1091         goto done;
1092
1093      do
1094      {
1095         this_block = direnum->block;
1096         this_index = direnum->index;
1097
1098         err = prodos_get_next_dirent(image, direnum, ent);
1099         if (err)
1100            goto done;
1101
1102         /* if we need to create a file entry and this is free, track it */
1103         if (create && this_block && !free_block && !ent->storage_type)
1104         {
1105            free_block = this_block;
1106            free_index = this_index;
1107         }
1108      }
1109      while(direnum->block && (strcmp(path, ent->filename) || (
1110         !is_file_storagetype(ent->storage_type) &&
1111         !is_dir_storagetype(ent->storage_type))));
1112
1113      old_path = path;
1114      path += strlen(path) + 1;   
1115      if (*path)
1116      {
1117         /* we have found part of the path; we are not finished yet */
1118         if (!is_dir_storagetype(ent->storage_type))
1119         {
1120            err = IMGTOOLERR_FILENOTFOUND;
1121            goto done;
1122         }
1123         block = ent->key_pointer[0];
1124      }
1125      else if (!direnum->block)
1126      {
1127         /* did not find file; maybe we need to create it */
1128         if (create == CREATE_NONE)
1129         {
1130            err = IMGTOOLERR_FILENOTFOUND;
1131            goto done;
1132         }
1133
1134         /* do we need to expand the directory? */
1135         if (!free_block)
1136         {
1137            if (this_block == 0)
1138            {
1139               err = IMGTOOLERR_CORRUPTFILE;
1140               goto done;
1141            }
1142
1143            err = prodos_load_block(image, this_block, buffer);
1144            if (err)
1145               goto done;
1146
1147            /* allocate a block */
1148            err = prodos_alloc_block(image, NULL, &free_block);
1149            if (err)
1150               goto done;
1151
1152            /* clear out this new block */
1153            err = prodos_clear_block(image, free_block);
1154            if (err)
1155               goto done;
1156
1157            /* save this link */
1158            place_integer_le(buffer, 2, 2, free_block);
1159            err = prodos_save_block(image, this_block, buffer);
1160            if (err)
1161               goto done;
1162
1163            free_index = 0;
1164         }
1165
1166         /* seek back to the free space */
1167         err = prodos_enum_seek(image, direnum, free_block, free_index);
1168         if (err)
1169            goto done;
1170
1171         new_file_block = 0;
1172         if (create == CREATE_DIR)
1173         {
1174            /* if we are creating a directory, we need to create a new block */
1175            err = prodos_alloc_block(image, NULL, &new_file_block);
1176            if (err)
1177               goto done;
1178
1179            err = prodos_clear_block(image, new_file_block);
1180            if (err)
1181               goto done;
1182         }
1183
1184         /* prepare the dirent */
1185         memset(ent, 0, sizeof(*ent));
1186         ent->storage_type = (create == CREATE_DIR) ? 0xe0 : 0x10;
1187         ent->creation_time = ent->lastmodified_time = prodos_time_now();
1188         ent->key_pointer[0] = new_file_block;
1189         ent->file_type = 0x3F3F3F3F;
1190         ent->file_creator = 0x3F3F3F3F;
1191         strncpy(ent->filename, old_path, sizeof(ent->filename) / sizeof(ent->filename[0]));
1192
1193         /* and place it */
1194         err = prodos_put_dirent(image, direnum, ent);
1195         if (err)
1196            goto done;
1197
1198         this_block = free_block;
1199         this_index = free_index;
1200      }
1201      else
1202      {
1203         /* we've found the file; seek that dirent */
1204         err = prodos_enum_seek(image, direnum, this_block, this_index);
1205         if (err)
1206            goto done;
1207      }
1208   }
1209
1210   err = IMGTOOLERR_SUCCESS;
1211done:
1212   return err;
1213}
1214
1215
1216
1217static imgtoolerr_t prodos_fill_file(imgtool_image *image, UINT8 *bitmap,
1218   UINT16 key_block, int key_block_allocated,
1219   int depth, UINT32 blockcount, UINT32 block_index)
1220{
1221   imgtoolerr_t err;
1222   prodos_diskinfo *di;
1223   int dirty;
1224   int sub_block_allocated;
1225   UINT16 i, sub_block, new_sub_block;
1226   UINT8 buffer[BLOCK_SIZE];
1227
1228   di = get_prodos_info(image);
1229
1230   if (key_block_allocated)
1231   {
1232      /* we are on a recently allocated key block; start fresh */
1233      memset(buffer, 0, sizeof(buffer));
1234      dirty = TRUE;
1235   }
1236   else
1237   {
1238      /* this is a preexisting key block */
1239      err = prodos_load_block(image, key_block, buffer);
1240      if (err)
1241         return err;
1242      dirty = FALSE;
1243   }
1244
1245   for (i = 0; i < 256; i++)
1246   {     
1247      sub_block_allocated = FALSE;
1248
1249      sub_block = buffer[i + 256];
1250      sub_block <<= 8;
1251      sub_block += buffer[i + 0];
1252
1253      new_sub_block = sub_block;
1254      if ((block_index < blockcount) && (sub_block == 0))
1255      {
1256         err = prodos_alloc_block(image, bitmap, &new_sub_block);
1257         if (err)
1258            return err;
1259         sub_block_allocated = TRUE;
1260      }
1261      else if ((block_index >= blockcount) && (sub_block != 0))
1262      {
1263         new_sub_block = 0;
1264         if (sub_block < di->total_blocks)
1265            prodos_set_volume_bitmap_bit(bitmap, sub_block, 0);
1266      }
1267
1268      /* did we change the block? */
1269      if (new_sub_block != sub_block)
1270      {
1271         dirty = TRUE;
1272         buffer[i + 0] = new_sub_block >> 0;
1273         buffer[i + 256] = new_sub_block >> 8;
1274         if (sub_block == 0)
1275            sub_block = new_sub_block;
1276      }
1277
1278      /* call recursive function */
1279      if (depth > 2)
1280      {
1281         err = prodos_fill_file(image, bitmap, sub_block, sub_block_allocated, depth - 1, blockcount, block_index);
1282         if (err)
1283            return err;
1284      }
1285
1286      /* increment index */
1287      block_index += 1 << ((depth - 2) * 8);
1288   }
1289
1290   /* if we changed anything, then save the block */
1291   if (dirty)
1292   {
1293      err = prodos_save_block(image, key_block, buffer);
1294      if (err)
1295         return err;
1296   }
1297   return IMGTOOLERR_SUCCESS;
1298}
1299
1300
1301
1302static imgtoolerr_t prodos_set_file_block_count(imgtool_image *image, prodos_direnum *direnum,
1303   prodos_dirent *ent, UINT8 *bitmap, int fork_num, UINT32 new_blockcount)
1304{
1305   imgtoolerr_t err;
1306   int depth, new_depth, i;
1307   UINT16 new_block, block;
1308   UINT8 buffer[BLOCK_SIZE];
1309   UINT16 key_pointer;
1310
1311   if (fork_num && (new_blockcount > 0) && !is_extendedfile_storagetype(ent->storage_type))
1312   {
1313      /* need to change a normal file to an extended file */
1314      err = prodos_promote_file(image, bitmap, ent);
1315      if (err)
1316         return err;
1317   }
1318
1319   key_pointer = ent->key_pointer[fork_num];
1320   depth = ent->depth[fork_num];
1321
1322   /* determine the new tree depth */
1323   if (new_blockcount <= 1)
1324      new_depth = 1;
1325   else if (new_blockcount <= 256)
1326      new_depth = 2;
1327   else
1328      new_depth = 3;
1329
1330   /* are we zero length, and do we have to create a block? */
1331   if ((new_blockcount >= 1) && (key_pointer == 0))
1332   {
1333      err = prodos_alloc_block(image, bitmap, &new_block);
1334      if (err)
1335         return err;
1336      key_pointer = new_block;
1337   }
1338
1339   /* do we have to grow the tree? */
1340   while(new_depth > depth)
1341   {
1342      err = prodos_alloc_block(image, bitmap, &new_block);
1343      if (err)
1344         return err;
1345
1346      /* create this new key block, with a link to the previous one */
1347      memset(buffer, 0, sizeof(buffer));
1348      buffer[0] = (UINT8) (key_pointer >> 0);
1349      buffer[256] = (UINT8) (key_pointer >> 8);
1350      err = prodos_save_block(image, new_block, buffer);
1351      if (err)
1352         return err;
1353
1354      depth++;
1355      key_pointer = new_block;
1356   }
1357
1358   /* do we have to shrink the tree? */
1359   while(new_depth < depth)
1360   {
1361      err = prodos_load_block(image, key_pointer, buffer);
1362      if (err)
1363         return err;
1364
1365      for (i = 1; i < 256; i++)
1366      {
1367         block = buffer[i + 256];
1368         block <<= 8;
1369         block |= buffer[i + 0];
1370
1371         if (block > 0)
1372         {
1373            if (depth > 2)
1374            {
1375               /* remove this block's children */
1376               err = prodos_fill_file(image, bitmap, block, FALSE, depth - 1, 0, 0);
1377               if (err)
1378                  return err;
1379            }
1380
1381            /* and remove this block */
1382            prodos_set_volume_bitmap_bit(bitmap, block, 0);
1383         }
1384      }
1385
1386      /* remove this key block */
1387      prodos_set_volume_bitmap_bit(bitmap, key_pointer, 0);
1388
1389      /* set the new key pointer */
1390      block = buffer[256];
1391      block <<= 8;
1392      block |= buffer[0];
1393      key_pointer = block;
1394   
1395      depth--;
1396   }
1397
1398   if (new_blockcount > 0)
1399   {
1400      /* fill out the file tree */
1401      err = prodos_fill_file(image, bitmap, key_pointer, FALSE, depth, new_blockcount, 0);
1402      if (err)
1403         return err;
1404   }
1405   else if (key_pointer != 0)
1406   {
1407      /* we are now zero length, and don't need a key pointer */
1408      prodos_set_volume_bitmap_bit(bitmap, key_pointer, 0);
1409      key_pointer = 0;
1410   }
1411
1412   /* change the depth if we are not an extended file */
1413   if (is_normalfile_storagetype(ent->storage_type))
1414   {
1415      ent->storage_type &= ~0xF0;
1416      ent->storage_type |= depth * 0x10;
1417   }
1418
1419   ent->key_pointer[fork_num] = key_pointer;
1420   ent->depth[fork_num] = depth;
1421   return IMGTOOLERR_SUCCESS;
1422}
1423
1424
1425
1426static imgtoolerr_t prodos_set_file_size(imgtool_image *image, prodos_direnum *direnum,
1427   prodos_dirent *ent, int fork_num, UINT32 new_size)
1428{
1429   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1430   UINT32 blockcount, new_blockcount;
1431   UINT8 *bitmap = NULL;
1432
1433   if (ent->filesize[fork_num] != new_size)
1434   {
1435      blockcount = (ent->filesize[fork_num] + BLOCK_SIZE - 1) / BLOCK_SIZE;
1436      new_blockcount = (new_size + BLOCK_SIZE - 1) / BLOCK_SIZE;
1437
1438      /* do we need to change the block chain? */
1439      if (new_blockcount != blockcount)
1440      {
1441         err = prodos_load_volume_bitmap(image, &bitmap);
1442         if (err)
1443            goto done;
1444
1445         err = prodos_set_file_block_count(image, direnum, ent, bitmap, fork_num, new_blockcount);
1446         if (err)
1447            goto done;
1448
1449         err = prodos_save_volume_bitmap(image, bitmap);
1450         if (err)
1451            goto done;
1452      }
1453
1454      ent->filesize[fork_num] = new_size;
1455      err = prodos_put_dirent(image, direnum, ent);
1456      if (err)
1457         goto done;
1458   }
1459
1460done:
1461   if (bitmap)
1462      free(bitmap);
1463   return err;
1464}
1465
1466
1467
1468static UINT32 prodos_get_storagetype_maxfilesize(UINT8 storage_type)
1469{
1470   UINT32 max_filesize = 0;
1471   switch(storage_type & 0xF0)
1472   {
1473      case 0x10:
1474         max_filesize = BLOCK_SIZE * 1;
1475         break;
1476      case 0x20:
1477         max_filesize = BLOCK_SIZE * 256;
1478         break;
1479      case 0x30:
1480      case 0x50:
1481         max_filesize = BLOCK_SIZE * 32768;
1482         break;
1483   }
1484   return max_filesize;
1485}
1486
1487
1488
1489static imgtoolerr_t prodos_diskimage_beginenum(imgtool_directory *enumeration, const char *path)
1490{
1491   imgtoolerr_t err;
1492   imgtool_image *image;
1493   prodos_direnum *appleenum;
1494   prodos_dirent ent;
1495   UINT16 block = ROOTDIR_BLOCK;
1496
1497   image = imgtool_directory_image(enumeration);
1498   appleenum = (prodos_direnum *) imgtool_directory_extrabytes(enumeration);
1499
1500   /* find subdirectory, if appropriate */
1501   if (*path)
1502   {
1503      err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
1504      if (err)
1505         return err;
1506
1507      /* only work on directories */
1508      if (!is_dir_storagetype(ent.storage_type))
1509         return IMGTOOLERR_FILENOTFOUND;
1510
1511      block = ent.key_pointer[0];
1512   }
1513
1514   /* seek initial block */
1515   err = prodos_enum_seek(image, appleenum, block, 0);
1516   if (err)
1517      return err;
1518
1519   return IMGTOOLERR_SUCCESS;
1520}
1521
1522
1523
1524static imgtoolerr_t prodos_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
1525{
1526   imgtoolerr_t err;
1527   imgtool_image *image;
1528   prodos_direnum *appleenum;
1529   prodos_dirent pd_ent;
1530   UINT32 max_filesize;
1531
1532   image = imgtool_directory_image(enumeration);
1533   appleenum = (prodos_direnum *) imgtool_directory_extrabytes(enumeration);
1534
1535   do
1536   {
1537      err = prodos_get_next_dirent(image, appleenum, &pd_ent);
1538      if (err)
1539         return err;
1540   }
1541   while(appleenum->block
1542      && !is_file_storagetype(pd_ent.storage_type)
1543      && !is_dir_storagetype(pd_ent.storage_type));
1544
1545   /* end of file? */
1546   if (pd_ent.storage_type == 0x00)
1547   {
1548      ent->eof = 1;
1549      return IMGTOOLERR_SUCCESS;
1550   }
1551
1552   strcpy(ent->filename, pd_ent.filename);
1553   ent->directory         = is_dir_storagetype(pd_ent.storage_type);
1554   ent->creation_time      = prodos_crack_time(pd_ent.creation_time);
1555   ent->lastmodified_time   = prodos_crack_time(pd_ent.lastmodified_time);
1556
1557   if (!ent->directory)
1558   {
1559      ent->filesize = pd_ent.filesize[0];
1560
1561      max_filesize = prodos_get_storagetype_maxfilesize(pd_ent.storage_type);
1562      if (ent->filesize > max_filesize)
1563      {
1564         ent->corrupt = 1;
1565         ent->filesize = max_filesize;
1566      }
1567   }
1568   return IMGTOOLERR_SUCCESS;
1569}
1570
1571
1572
1573static imgtoolerr_t prodos_read_file_tree(imgtool_image *image, UINT32 *filesize,
1574   UINT32 block, int nest_level, imgtool_stream *destf)
1575{
1576   imgtoolerr_t err;
1577   prodos_diskinfo *di;
1578   UINT8 buffer[BLOCK_SIZE];
1579   UINT16 sub_block;
1580   size_t bytes_to_write;
1581   int i;
1582
1583   /* check bounds */
1584   di = get_prodos_info(image);
1585   if (block >= di->total_blocks)
1586      return IMGTOOLERR_CORRUPTFILE;
1587
1588   err = prodos_load_block(image, block, buffer);
1589   if (err)
1590      return err;
1591
1592   if (nest_level > 0)
1593   {
1594      /* this is an index block */
1595      for (i = 0; i < 256; i++)
1596      {
1597         /* retrieve the block pointer; the two bytes are on either half
1598          * of the block */
1599         sub_block = buffer[i + 256];
1600         sub_block <<= 8;
1601         sub_block |= buffer[i + 0];
1602
1603         if (sub_block != 0)
1604         {
1605            err = prodos_read_file_tree(image, filesize, sub_block, nest_level - 1, destf);
1606            if (err)
1607               return err;
1608         }
1609      }
1610   }
1611   else
1612   {
1613      /* this is a leaf block */
1614      bytes_to_write = MIN(*filesize, sizeof(buffer));
1615      stream_write(destf, buffer, bytes_to_write);
1616      *filesize -= bytes_to_write;
1617   }
1618   return IMGTOOLERR_SUCCESS;
1619}
1620
1621
1622
1623static imgtoolerr_t prodos_write_file_tree(imgtool_image *image, UINT32 *filesize,
1624   UINT32 block, int nest_level, imgtool_stream *sourcef)
1625{
1626   imgtoolerr_t err;
1627   prodos_diskinfo *di;
1628   UINT8 buffer[BLOCK_SIZE];
1629   UINT16 sub_block;
1630   size_t bytes_to_read;
1631   int i;
1632
1633   /* nothing more to read? bail */
1634   if (*filesize == 0)
1635      return IMGTOOLERR_SUCCESS;
1636
1637   /* check bounds */
1638   di = get_prodos_info(image);
1639   if (block >= di->total_blocks)
1640      return IMGTOOLERR_CORRUPTFILE;
1641
1642   err = prodos_load_block(image, block, buffer);
1643   if (err)
1644      return err;
1645
1646   if (nest_level > 0)
1647   {
1648      for (i = 0; i < 256; i++)
1649      {
1650         sub_block = buffer[i + 256];
1651         sub_block <<= 8;
1652         sub_block |= buffer[i + 0];
1653
1654         if (sub_block != 0)
1655         {
1656            err = prodos_write_file_tree(image, filesize, sub_block, nest_level - 1, sourcef);
1657            if (err)
1658               return err;
1659         }
1660      }
1661   }
1662   else
1663   {
1664      /* this is a leaf block */
1665      bytes_to_read = MIN(*filesize, sizeof(buffer));
1666      stream_read(sourcef, buffer, bytes_to_read);
1667      *filesize -= bytes_to_read;
1668
1669      err = prodos_save_block(image, block, buffer);
1670      if (err)
1671         return err;
1672   }
1673   return IMGTOOLERR_SUCCESS;
1674}
1675
1676
1677
1678static imgtoolerr_t prodos_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
1679{
1680   imgtoolerr_t err;
1681   imgtool_image *image = imgtool_partition_image(partition);
1682   prodos_diskinfo *di;
1683   UINT8 *bitmap = NULL;
1684   UINT16 i;
1685
1686   di = get_prodos_info(image);
1687   *size = 0;
1688
1689   err = prodos_load_volume_bitmap(image, &bitmap);
1690   if (err)
1691      goto done;
1692
1693   for (i = 0; i < di->total_blocks; i++)
1694   {
1695      if (!prodos_get_volume_bitmap_bit(bitmap, i))
1696         *size += BLOCK_SIZE;
1697   }
1698
1699done:
1700   if (bitmap)
1701      free(bitmap);
1702   return err;
1703}
1704
1705
1706
1707static imgtoolerr_t prodos_diskimage_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
1708{
1709   imgtoolerr_t err;
1710   imgtool_image *image = imgtool_partition_image(partition);
1711   prodos_dirent ent;
1712   UINT16 key_pointer;
1713   int nest_level;
1714   mac_fork_t fork_num;
1715
1716   err = prodos_lookup_path(image, filename, CREATE_NONE, NULL, &ent);
1717   if (err)
1718      return err;
1719
1720   if (is_dir_storagetype(ent.storage_type))
1721      return IMGTOOLERR_FILENOTFOUND;
1722
1723   err = mac_identify_fork(fork, &fork_num);
1724   if (err)
1725      return err;
1726
1727   key_pointer = ent.key_pointer[fork_num];
1728   nest_level = ent.depth[fork_num] - 1;
1729
1730   if (key_pointer != 0)
1731   {
1732      err = prodos_read_file_tree(image, &ent.filesize[fork_num], key_pointer,
1733         nest_level, destf);
1734      if (err)
1735         return err;
1736   }
1737
1738   /* have we not actually received the correct amount of bytes? if not, fill in the rest */
1739   if (ent.filesize[fork_num] > 0)
1740      stream_fill(destf, 0, ent.filesize[fork_num]);
1741
1742   return IMGTOOLERR_SUCCESS;
1743}
1744
1745
1746
1747static imgtoolerr_t prodos_diskimage_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
1748{
1749   imgtoolerr_t err;
1750   imgtool_image *image = imgtool_partition_image(partition);
1751   prodos_dirent ent;
1752   prodos_direnum direnum;
1753   UINT64 file_size;
1754   mac_fork_t fork_num;
1755
1756   file_size = stream_size(sourcef);
1757
1758   err = prodos_lookup_path(image, filename, CREATE_FILE, &direnum, &ent);
1759   if (err)
1760      return err;
1761
1762   /* only work on files */
1763   if (is_dir_storagetype(ent.storage_type))
1764      return IMGTOOLERR_FILENOTFOUND;
1765
1766   err = mac_identify_fork(fork, &fork_num);
1767   if (err)
1768      return err;
1769
1770   /* set the file size */
1771   err = prodos_set_file_size(image, &direnum, &ent, fork_num, file_size);
1772   if (err)
1773      return err;
1774
1775   err = prodos_write_file_tree(image, &ent.filesize[fork_num], ent.key_pointer[fork_num],
1776      ent.depth[fork_num] - 1, sourcef);
1777   if (err)
1778      return err;
1779
1780   return IMGTOOLERR_SUCCESS;
1781}
1782
1783
1784
1785static imgtoolerr_t prodos_diskimage_deletefile(imgtool_partition *partition, const char *path)
1786{
1787   imgtoolerr_t err;
1788   imgtool_image *image = imgtool_partition_image(partition);
1789   prodos_dirent ent;
1790   prodos_direnum direnum;
1791
1792   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
1793   if (err)
1794      return err;
1795
1796   /* only work on files */
1797   if (is_dir_storagetype(ent.storage_type))
1798      return IMGTOOLERR_FILENOTFOUND;
1799
1800   /* empty out both forks */
1801   err = prodos_set_file_size(image, &direnum, &ent, 0, 0);
1802   if (err)
1803      return err;
1804   err = prodos_set_file_size(image, &direnum, &ent, 1, 0);
1805   if (err)
1806      return err;
1807
1808   memset(&ent, 0, sizeof(ent));
1809   err = prodos_put_dirent(image, &direnum, &ent);
1810   if (err)
1811      return err;
1812
1813   return IMGTOOLERR_SUCCESS;
1814}
1815
1816
1817
1818static imgtoolerr_t prodos_diskimage_listforks(imgtool_partition *partition, const char *path, imgtool_forkent *ents, size_t len)
1819{
1820   imgtoolerr_t err;
1821   imgtool_image *image = imgtool_partition_image(partition);
1822   prodos_dirent ent;
1823   prodos_direnum direnum;
1824   int fork_num = 0;
1825
1826   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
1827   if (err)
1828      return err;
1829
1830   if (is_dir_storagetype(ent.storage_type))
1831      return IMGTOOLERR_FILENOTFOUND;
1832
1833   /* specify data fork */
1834   ents[fork_num].type = FORK_DATA;
1835   ents[fork_num].forkname[0] = '\0';
1836   ents[fork_num].size = ent.filesize[0];
1837   fork_num++;
1838
1839   if (is_extendedfile_storagetype(ent.storage_type))
1840   {
1841      /* specify the resource fork */
1842      ents[fork_num].type = FORK_RESOURCE;
1843      strcpy(ents[fork_num].forkname, "RESOURCE_FORK");
1844      ents[fork_num].size = ent.filesize[1];
1845      fork_num++;
1846   }
1847
1848   ents[fork_num].type = FORK_END;
1849   return IMGTOOLERR_SUCCESS;
1850}
1851
1852
1853
1854static imgtoolerr_t prodos_diskimage_createdir(imgtool_partition *partition, const char *path)
1855{
1856   imgtoolerr_t err;
1857   imgtool_image *image = imgtool_partition_image(partition);
1858   prodos_dirent ent;
1859   prodos_direnum direnum;
1860
1861   err = prodos_lookup_path(image, path, CREATE_DIR, &direnum, &ent);
1862   if (err)
1863      return err;
1864
1865   /* only work on directories */
1866   if (!is_dir_storagetype(ent.storage_type))
1867      return IMGTOOLERR_FILENOTFOUND;
1868
1869   return IMGTOOLERR_SUCCESS;
1870}
1871
1872
1873
1874static imgtoolerr_t prodos_free_directory(imgtool_image *image, UINT8 *volume_bitmap, UINT16 key_pointer)
1875{
1876   imgtoolerr_t err;
1877   prodos_diskinfo *di;
1878   int i;
1879   UINT16 next_block;
1880   UINT32 offset;
1881   UINT8 buffer[BLOCK_SIZE];
1882
1883   di = get_prodos_info(image);
1884
1885   if (key_pointer != 0)
1886   {
1887      err = prodos_load_block(image, key_pointer, buffer);
1888      if (err)
1889         return err;
1890
1891      for (i = 0; i < di->dirents_per_block; i++)
1892      {
1893         offset = i * di->dirent_size + 4;
1894
1895         if (is_file_storagetype(buffer[offset]) || is_file_storagetype(buffer[offset]))
1896            return IMGTOOLERR_DIRNOTEMPTY;
1897      }
1898
1899      next_block = pick_integer_le(buffer, 2, 2);
1900
1901      err = prodos_free_directory(image, volume_bitmap, next_block);
1902      if (err)
1903         return err;
1904
1905      prodos_set_volume_bitmap_bit(volume_bitmap, key_pointer, 0);
1906   }
1907   return IMGTOOLERR_SUCCESS;
1908}
1909
1910
1911
1912static imgtoolerr_t prodos_diskimage_deletedir(imgtool_partition *partition, const char *path)
1913{
1914   imgtoolerr_t err;
1915   imgtool_image *image = imgtool_partition_image(partition);
1916   prodos_dirent ent;
1917   prodos_direnum direnum;
1918   UINT8 *volume_bitmap = NULL;
1919
1920   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
1921   if (err)
1922      goto done;
1923
1924   /* only work on directories */
1925   if (!is_dir_storagetype(ent.storage_type))
1926   {
1927      err = IMGTOOLERR_FILENOTFOUND;
1928      goto done;
1929   }
1930
1931   err = prodos_load_volume_bitmap(image, &volume_bitmap);
1932   if (err)
1933      goto done;
1934
1935   err = prodos_free_directory(image, volume_bitmap, ent.key_pointer[0]);
1936   if (err)
1937      goto done;
1938
1939   err = prodos_save_volume_bitmap(image, volume_bitmap);
1940   if (err)
1941      goto done;
1942
1943   memset(&ent, 0, sizeof(ent));
1944   err = prodos_put_dirent(image, &direnum, &ent);
1945   if (err)
1946      goto done;
1947
1948done:
1949   if (volume_bitmap)
1950      free(volume_bitmap);
1951   return IMGTOOLERR_SUCCESS;
1952}
1953
1954
1955
1956static imgtoolerr_t prodos_get_file_tree(imgtool_image *image, imgtool_chainent *chain, size_t chain_size,
1957   size_t *chain_pos, UINT16 block, UINT8 total_depth, UINT8 cur_depth)
1958{
1959   imgtoolerr_t err;
1960   prodos_diskinfo *di;
1961   int i;
1962   UINT16 sub_block;
1963   UINT8 buffer[BLOCK_SIZE];
1964
1965   if (block == 0)
1966      return IMGTOOLERR_SUCCESS;
1967   if (*chain_pos >= chain_size)
1968      return IMGTOOLERR_SUCCESS;
1969
1970   /* check bounds */
1971   di = get_prodos_info(image);
1972   if (block >= di->total_blocks)
1973      return IMGTOOLERR_CORRUPTFILE;
1974
1975   chain[*chain_pos].level = cur_depth;
1976   chain[*chain_pos].block = block;
1977   (*chain_pos)++;
1978
1979   /* must we recurse into the tree? */
1980   if (cur_depth < total_depth)
1981   {
1982      err = prodos_load_block(image, block, buffer);
1983      if (err)
1984         return err;
1985
1986      for (i = 0; i < 256; i++)
1987      {
1988         sub_block = buffer[i + 256];
1989         sub_block <<= 8;
1990         sub_block |= buffer[i + 0];
1991
1992         err = prodos_get_file_tree(image, chain, chain_size, chain_pos, sub_block, total_depth, cur_depth + 1);
1993         if (err)
1994            return err;
1995      }
1996   }
1997   return IMGTOOLERR_SUCCESS;
1998}
1999
2000
2001
2002static imgtoolerr_t prodos_diskimage_getattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, imgtool_attribute *values)
2003{
2004   imgtoolerr_t err;
2005   imgtool_image *image = imgtool_partition_image(partition);
2006   prodos_dirent ent;
2007   int i;
2008
2009   err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
2010   if (err)
2011      return err;
2012
2013   for (i = 0; attrs[i]; i++)
2014   {
2015      switch(attrs[i])
2016      {
2017         case IMGTOOLATTR_INT_MAC_TYPE:
2018            values[i].i = ent.file_type;
2019            break;
2020         case IMGTOOLATTR_INT_MAC_CREATOR:
2021            values[i].i = ent.file_creator;
2022            break;
2023         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
2024            values[i].i = ent.finder_flags;
2025            break;
2026         case IMGTOOLATTR_INT_MAC_COORDX:
2027            values[i].i = ent.coord_x;
2028            break;
2029         case IMGTOOLATTR_INT_MAC_COORDY:
2030            values[i].i = ent.coord_y;
2031            break;
2032         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
2033            values[i].i = ent.finder_folder;
2034            break;
2035         case IMGTOOLATTR_INT_MAC_ICONID:
2036            values[i].i = ent.icon_id;
2037            break;
2038         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
2039            values[i].i = ent.script_code;
2040            break;
2041         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
2042            values[i].i = ent.extended_flags;
2043            break;
2044         case IMGTOOLATTR_INT_MAC_COMMENTID:
2045            values[i].i = ent.comment_id;
2046            break;
2047         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
2048            values[i].i = ent.putaway_directory;
2049            break;
2050
2051         case IMGTOOLATTR_TIME_CREATED:
2052            values[i].t = prodos_crack_time(ent.creation_time);
2053            break;
2054         case IMGTOOLATTR_TIME_LASTMODIFIED:
2055            values[i].t = prodos_crack_time(ent.lastmodified_time);
2056            break;
2057      }
2058   }
2059
2060   return IMGTOOLERR_SUCCESS;
2061}
2062
2063
2064
2065static imgtoolerr_t prodos_diskimage_setattrs(imgtool_partition *partition, const char *path, const UINT32 *attrs, const imgtool_attribute *values)
2066{
2067   imgtoolerr_t err;
2068   imgtool_image *image = imgtool_partition_image(partition);
2069   prodos_dirent ent;
2070   prodos_direnum direnum;
2071   int i;
2072
2073   err = prodos_lookup_path(image, path, CREATE_NONE, &direnum, &ent);
2074   if (err)
2075      return err;
2076
2077   for (i = 0; attrs[i]; i++)
2078   {
2079      switch(attrs[i])
2080      {
2081         case IMGTOOLATTR_INT_MAC_TYPE:
2082            ent.file_type = values[i].i;
2083            break;
2084         case IMGTOOLATTR_INT_MAC_CREATOR:
2085            ent.file_creator = values[i].i;
2086            break;
2087         case IMGTOOLATTR_INT_MAC_FINDERFLAGS:
2088            ent.finder_flags = values[i].i;
2089            break;
2090         case IMGTOOLATTR_INT_MAC_COORDX:
2091            ent.coord_x = values[i].i;
2092            break;
2093         case IMGTOOLATTR_INT_MAC_COORDY:
2094            ent.coord_y = values[i].i;
2095            break;
2096         case IMGTOOLATTR_INT_MAC_FINDERFOLDER:
2097            ent.finder_folder = values[i].i;
2098            break;
2099         case IMGTOOLATTR_INT_MAC_ICONID:
2100            ent.icon_id = values[i].i;
2101            break;
2102         case IMGTOOLATTR_INT_MAC_SCRIPTCODE:
2103            ent.script_code = values[i].i;
2104            break;
2105         case IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS:
2106            ent.extended_flags = values[i].i;
2107            break;
2108         case IMGTOOLATTR_INT_MAC_COMMENTID:
2109            ent.comment_id = values[i].i;
2110            break;
2111         case IMGTOOLATTR_INT_MAC_PUTAWAYDIRECTORY:
2112            ent.putaway_directory = values[i].i;
2113            break;
2114
2115         case IMGTOOLATTR_TIME_CREATED:
2116            ent.creation_time = prodos_setup_time(values[i].t);
2117            break;
2118         case IMGTOOLATTR_TIME_LASTMODIFIED:
2119            ent.lastmodified_time = prodos_setup_time(values[i].t);
2120            break;
2121      }
2122   }
2123
2124   err = prodos_put_dirent(image, &direnum, &ent);
2125   if (err)
2126      return err;
2127
2128   return IMGTOOLERR_SUCCESS;}
2129
2130
2131
2132static imgtoolerr_t prodos_diskimage_suggesttransfer(imgtool_partition *partition, const char *path, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
2133{
2134   imgtoolerr_t err;
2135   imgtool_image *image = imgtool_partition_image(partition);
2136   prodos_dirent ent;
2137   mac_filecategory_t file_category = MAC_FILECATEGORY_DATA;
2138
2139   if (path)
2140   {
2141      err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
2142      if (err)
2143         return err;
2144
2145      file_category = is_extendedfile_storagetype(ent.storage_type)
2146         ? MAC_FILECATEGORY_FORKED : MAC_FILECATEGORY_DATA;
2147   }
2148
2149   mac_suggest_transfer(file_category, suggestions, suggestions_length);
2150   return IMGTOOLERR_SUCCESS;
2151}
2152
2153
2154
2155static imgtoolerr_t   prodos_diskimage_getchain(imgtool_partition *partition, const char *path, imgtool_chainent *chain, size_t chain_size)
2156{
2157   imgtoolerr_t err;
2158   imgtool_image *image = imgtool_partition_image(partition);
2159   prodos_dirent ent;
2160   size_t chain_pos = 0;
2161   mac_fork_t fork_num;
2162
2163   err = prodos_lookup_path(image, path, CREATE_NONE, NULL, &ent);
2164   if (err)
2165      return err;
2166
2167   switch(ent.storage_type & 0xF0)
2168   {
2169      case 0x10:
2170      case 0x20:
2171      case 0x30:
2172         /* normal ProDOS file */
2173         err = prodos_get_file_tree(image, chain, chain_size, &chain_pos,
2174            ent.key_pointer[0], ent.depth[0] - 1, 0);
2175         if (err)
2176            return err;
2177         break;
2178     
2179      case 0x50:
2180         /* extended ProDOS file */
2181         chain[chain_pos].level = 0;
2182         chain[chain_pos].block = ent.extkey_pointer;
2183         chain_pos++;
2184
2185         for (fork_num = 0; fork_num <= 1; fork_num++)
2186         {
2187            if (ent.key_pointer[fork_num])
2188            {
2189               err = prodos_get_file_tree(image, chain, chain_size, &chain_pos,
2190                  ent.key_pointer[fork_num], ent.depth[fork_num] - 1, 1);
2191               if (err)
2192                  return err;
2193            }
2194         }
2195         break;
2196
2197      case 0xE0:
2198         /* directory */
2199         return IMGTOOLERR_UNIMPLEMENTED;
2200
2201      default:
2202         return IMGTOOLERR_UNEXPECTED;
2203   }
2204
2205   return IMGTOOLERR_SUCCESS;
2206}
2207
2208
2209
2210static void generic_prodos_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2211{
2212   switch(state)
2213   {
2214      /* --- the following bits of info are returned as 64-bit signed integers --- */
2215      case IMGTOOLINFO_INT_INITIAL_PATH_SEPARATOR:      info->i = 1; break;
2216      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
2217      case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME:      info->i = 1; break;
2218      case IMGTOOLINFO_INT_SUPPORTS_LASTMODIFIED_TIME:   info->i = 1; break;
2219      case IMGTOOLINFO_INT_WRITING_UNTESTED:            info->i = 1; break;
2220      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(prodos_diskinfo); break;
2221      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(prodos_direnum); break;
2222      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = '/'; break;
2223
2224      /* --- the following bits of info are returned as NULL-terminated strings --- */
2225      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "ProDOS format"); break;
2226      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
2227      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
2228
2229      /* --- the following bits of info are returned as pointers to data or functions --- */
2230      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
2231      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = prodos_diskimage_beginenum; break;
2232      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = prodos_diskimage_nextenum; break;
2233      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = prodos_diskimage_freespace; break;
2234      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = prodos_diskimage_readfile; break;
2235      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = prodos_diskimage_writefile; break;
2236      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = prodos_diskimage_deletefile; break;
2237      case IMGTOOLINFO_PTR_LIST_FORKS:               info->list_forks = prodos_diskimage_listforks; break;
2238      case IMGTOOLINFO_PTR_CREATE_DIR:               info->create_dir = prodos_diskimage_createdir; break;
2239      case IMGTOOLINFO_PTR_DELETE_DIR:               info->delete_dir = prodos_diskimage_deletedir; break;
2240      case IMGTOOLINFO_PTR_GET_ATTRS:                  info->get_attrs = prodos_diskimage_getattrs; break;
2241      case IMGTOOLINFO_PTR_SET_ATTRS:                  info->set_attrs = prodos_diskimage_setattrs; break;
2242      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = prodos_diskimage_suggesttransfer; break;
2243      case IMGTOOLINFO_PTR_GET_CHAIN:                  info->get_chain = prodos_diskimage_getchain; break;
2244   }
2245}
2246
2247
2248
2249void prodos_525_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2250{
2251   switch(state)
2252   {
2253      /* --- the following bits of info are returned as NULL-terminated strings --- */
2254      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "prodos_525"); break;
2255
2256      /* --- the following bits of info are returned as pointers to data or functions --- */
2257      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = prodos_diskimage_create_525; break;
2258      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = prodos_diskimage_open_525; break;
2259      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_apple2; break;
2260
2261      default:                                 generic_prodos_get_info(imgclass, state, info); break;
2262   }
2263}
2264
2265
2266
2267void prodos_35_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2268{
2269   switch(state)
2270   {
2271      /* --- the following bits of info are returned as NULL-terminated strings --- */
2272      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "prodos_35"); break;
2273
2274      /* --- the following bits of info are returned as pointers to data or functions --- */
2275      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = prodos_diskimage_create_35; break;
2276      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = prodos_diskimage_open_35; break;
2277      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_apple35_iigs; break;
2278
2279      default:                                 generic_prodos_get_info(imgclass, state, info); break;
2280   }
2281}
src/mess/tools/imgtool/modules/msx_dsk.c
r0r1340
1/*
2 * msx_dsk.c : converts .ddi/.img/.msx/multidisk disk images to .dsk image
3 *
4 * Sean Young 2001
5 */
6
7/*
8 * .msx files are a certain type of disk dumps. They always seem to be
9 * double sided 720kB ones. There are no extra headers, but the order of
10 * the sectors is all messed up. This little program should put that
11 * straight. :)
12 *
13 * The structure is as follows: the first 9 sectors (=0x1200 bytes) of the
14 * first side, then the first 9 sectors of the other side, the next 9
15 * sectors of the first site, the next 9 sectors of the other side.. etc.
16 *
17 * These weird .msx files are found at: ftp://jazz.snu.ac.kr/pub/msx/
18 */
19
20/*
21 * .ddi DiskDupe images are always double sided 720kB images (at least in the
22 * MSX world). There is a header of 0x1200 bytes (in the version known to the
23 * MSX world; this is version is 5.12 -- and probably others). This format
24 * is used by the CompuJunks MSX2 emulator (MSX2EMUL).
25 *
26 * The exact format of the header is unknown to me. However, this does not
27 * seem to be important; the last 720kB is a complete continuous dump of
28 * the disk.
29 */
30
31/*
32 * .img files have the following format: first a one byte header, which
33 * is 1 (01h) for singled sided 360kB images, and 2 (02h) for double sided
34 * 720kB images. These files can be found at ftp://ftp.funet.fi/pub/msx/
35 */
36
37/*
38 * .dsk multidisks are used by fmsx-dos 1.6. These files are always double
39 * sided 3.5" disks (720kB), simply appended to one another.
40 */
41
42#include <assert.h>
43#include "osdepend.h"
44#include "imgtoolx.h"
45#include "utils.h"
46
47
48typedef struct {
49   imgtool_image         base;
50   char         *file_name;
51   imgtool_stream          *file_handle;
52   int          size, format, disks;
53   } DSK_IMAGE;
54
55typedef struct
56   {
57   imgtool_directory    base;
58   DSK_IMAGE   *image;
59   int         index;
60   } DSK_ITERATOR;
61
62static int msx_dsk_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
63static void msx_dsk_image_exit(imgtool_image *img);
64static int msx_dsk_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
65static int msx_dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
66static void msx_dsk_image_closeenum(imgtool_directory *enumeration);
67static int msx_dsk_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
68
69IMAGEMODULE(
70   msx_img,
71   "MSX .img diskimage",            /* human readable name */
72   "img",                        /* file extension */
73   NULL,                        /* crcfile */
74   NULL,                        /* crc system name */
75   NULL,                        /* eoln */
76   0,                           /* flags */
77   msx_dsk_image_init,               /* init function */
78   msx_dsk_image_exit,               /* exit function */
79   NULL,                        /* info function */
80   msx_dsk_image_beginenum,         /* begin enumeration */
81   msx_dsk_image_nextenum,            /* enumerate next */
82   msx_dsk_image_closeenum,         /* close enumeration */
83   NULL,                        /* free space on image */
84   msx_dsk_image_readfile,            /* read file */
85   NULL,                        /* write file */
86   NULL,                        /* delete file */
87   NULL,                        /* create image */
88   NULL,                        /* read sector */
89   NULL,                        /* write sector */
90   NULL,                        /* file options */
91   NULL                        /* create options */
92)
93
94IMAGEMODULE(
95   msx_ddi,
96   "MSX DiskDupe .ddi diskimage",      /* human readable name */
97   "ddi",                        /* file extension */
98   NULL,                        /* crcfile */
99   NULL,                        /* crc system name */
100   NULL,                        /* eoln */
101   0,                           /* flags */
102   msx_dsk_image_init,               /* init function */
103   msx_dsk_image_exit,               /* exit function */
104   NULL,                        /* info function */
105   msx_dsk_image_beginenum,         /* begin enumeration */
106   msx_dsk_image_nextenum,            /* enumerate next */
107   msx_dsk_image_closeenum,         /* close enumeration */
108   NULL,                        /* free space on image */
109   msx_dsk_image_readfile,            /* read file */
110   NULL,                        /* write file */
111   NULL,                        /* delete file */
112   NULL,                        /* create image */
113   NULL,                        /* read sector */
114   NULL,                        /* write sector */
115   NULL,                        /* file options */
116   NULL                        /* create options */
117)
118
119IMAGEMODULE(
120   msx_msx,
121   "MSX .msx diskimage",            /* human readable name */
122   "ddi",                        /* file extension */
123   NULL,                        /* crcfile */
124   NULL,                        /* crc system name */
125   NULL,                        /* eoln */
126   0,                           /* flags */
127   msx_dsk_image_init,               /* init function */
128   msx_dsk_image_exit,               /* exit function */
129   NULL,                        /* info function */
130   msx_dsk_image_beginenum,         /* begin enumeration */
131   msx_dsk_image_nextenum,            /* enumerate next */
132   msx_dsk_image_closeenum,         /* close enumeration */
133   NULL,                        /* free space on image */
134   msx_dsk_image_readfile,            /* read file */
135   NULL,                        /* write file */
136   NULL,                        /* delete file */
137   NULL,                        /* create image */
138   NULL,                        /* read sector */
139   NULL,                        /* write sector */
140   NULL,                        /* file options */
141   NULL                        /* create options */
142)
143
144IMAGEMODULE(
145   msx_mul,
146   "MSX multi disk image",            /* human readable name */
147   "dsk",                        /* file extension */
148   NULL,                        /* crcfile */
149   NULL,                        /* crc system name */
150   NULL,                        /* eoln */
151   0,                           /* flags */
152   msx_dsk_image_init,               /* init function */
153   msx_dsk_image_exit,               /* exit function */
154   NULL,                        /* info function */
155   msx_dsk_image_beginenum,         /* begin enumeration */
156   msx_dsk_image_nextenum,            /* enumerate next */
157   msx_dsk_image_closeenum,         /* close enumeration */
158   NULL,                        /* free space on image */
159   msx_dsk_image_readfile,            /* read file */
160   NULL,                        /* write file */
161   NULL,                        /* delete file */
162   NULL,                        /* create image */
163   NULL,                        /* read sector */
164   NULL,                        /* write sector */
165   NULL,                        /* file options */
166   NULL                        /* create options */
167)
168
169#define    FORMAT_IMG      (0)
170#define    FORMAT_DDI      (1)
171#define    FORMAT_MSX      (2)
172#define    FORMAT_MULTI   (3)
173
174static int msx_dsk_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
175{
176   DSK_IMAGE *image;
177   int size, disks, correct, format;
178    UINT8 header;
179
180   size = stream_size (f);
181   if (size < (360*1024) )
182      return IMGTOOLERR_MODULENOTFOUND;
183   
184   disks = 1;
185
186   correct = 0;
187
188   if (!strcmp(mod->name, "msx_img"))
189   {
190      format = FORMAT_IMG;
191      if (1 != stream_read (f, &header, 1) )
192         return IMGTOOLERR_READERROR;
193
194      if ( (size == (720*1024+1) ) && (header == 2) )
195         {
196         correct = 1;
197         size--;
198         }
199      if ( (size == (360*1024+1) ) && (header == 1) )
200         {
201         correct = 1;
202         size--;
203         }
204   }
205   else if (!strcmp(mod->name, "msx_msx"))
206   {
207      format = FORMAT_MSX;
208      if (size == (720*1024) )
209         correct = 1;
210   }
211   else if (!strcmp(mod->name, "msx_ddi"))
212   {
213      format = FORMAT_DDI;
214      if (size == (720*1024+0x1200) )
215         {
216         size -= 0x1200;
217         correct = 1;
218         }
219   }
220   else if (!strcmp(mod->name, "msx_mul"))
221   {
222      format = FORMAT_MULTI;
223      if ( (size > 720*1024) && !(size % (720*1024) ) )
224         {
225         disks = size / (720*1024);
226         correct = 1;
227         size = 720*1024;
228         }
229   }
230   else
231   {
232      assert(0);
233      return IMGTOOLERR_UNEXPECTED;
234   }
235   
236   if (!correct) return IMGTOOLERR_MODULENOTFOUND;
237
238   image = (DSK_IMAGE*)malloc (sizeof (DSK_IMAGE) );
239   if (!image) return IMGTOOLERR_OUTOFMEMORY;
240
241   *outimg = (imgtool_image*)image;
242
243   memset(image, 0, sizeof(DSK_IMAGE));
244   image->base.module = mod;
245   image->file_handle = f;
246   image->size = size;
247   image->format = format;
248   image->file_name = NULL;
249   image->disks = disks;
250
251   return 0;
252   }
253
254static void msx_dsk_image_exit(imgtool_image *img)
255   {
256   DSK_IMAGE *image=(DSK_IMAGE*)img;
257   stream_close(image->file_handle);
258   if (image->file_name) free(image->file_name);
259   free(image);
260   }
261
262static int msx_dsk_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
263   {
264   DSK_IMAGE *image=(DSK_IMAGE*)img;
265   DSK_ITERATOR *iter;
266
267   iter=*(DSK_ITERATOR**)outenum = (DSK_ITERATOR*) malloc(sizeof(DSK_ITERATOR));
268   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
269
270   iter->base.module = image->base.module;
271   iter->image=image;
272   iter->index = 1;
273
274   return 0;
275   }
276
277static int msx_dsk_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
278   {
279   DSK_ITERATOR *iter=(DSK_ITERATOR*)enumeration;
280
281   ent->eof = (iter->index > iter->image->disks);
282   if (!ent->eof)
283      {
284      if (iter->image->file_name)
285         strcpy (ent->fname, iter->image->file_name);
286      else
287         {
288         if (iter->image->disks ==  1)
289            strcpy (ent->fname, "msx.dsk");
290         else
291            sprintf (ent->fname, "msx-%d.dsk", iter->index);
292         }
293
294      ent->corrupt=0;
295      ent->filesize = iter->image->size;
296
297      iter->index++;
298      }
299
300   return 0;
301   }
302
303static void msx_dsk_image_closeenum(imgtool_directory *enumeration)
304   {
305   free(enumeration);
306   }
307
308static int msx_dsk_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
309   {
310   DSK_IMAGE *image=(DSK_IMAGE*)img;
311   UINT8   buf[0x1200];
312   int    i, offset, n1, n2, disks = 0;
313
314   /*  check file name */
315   switch (image->format)
316      {
317      case FORMAT_IMG:
318      case FORMAT_DDI:
319      case FORMAT_MSX:
320         if (strcmpi (fname, "msx.dsk") )
321            return IMGTOOLERR_MODULENOTFOUND;
322         break;
323      case FORMAT_MULTI:
324         if (strncmpi (fname, "msx-", 4) )
325            return IMGTOOLERR_MODULENOTFOUND;
326         offset = 4; disks = 0;
327         while ( (fname[offset] >= '0') || (fname[offset] <= '9') )
328            disks = disks * 10 + (fname[offset++] - '0');
329
330         if (mame_stricmp (fname + offset, ".dsk") )
331            return IMGTOOLERR_MODULENOTFOUND;
332
333         if ( (disks < 1) || (disks > image->disks) )
334            return IMGTOOLERR_MODULENOTFOUND;
335
336         break;
337      }
338
339   /* copy the file */
340   switch (image->format)
341      {
342      case FORMAT_MSX:
343         i = 80; n1 = 0; n2 = 80;
344         while (i--)
345            {
346            stream_seek (image->file_handle, n1++ * 0x1200, SEEK_SET);
347            if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
348               return IMGTOOLERR_READERROR;
349
350            if (0x1200 != stream_write (destf, buf, 0x1200) )
351               return IMGTOOLERR_WRITEERROR;
352
353            stream_seek (image->file_handle, n2++ * 0x1200, SEEK_SET);
354            if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
355               return IMGTOOLERR_READERROR;
356
357            if (0x1200 != stream_write (destf, buf, 0x1200) )
358               return IMGTOOLERR_WRITEERROR;
359            }
360
361         return 0;
362      case FORMAT_IMG:
363         offset = 1; i = (image->size / 0x1200);
364         break;
365      case FORMAT_DDI:
366         offset = 0x1200; i = 160;
367         break;
368      case FORMAT_MULTI:   /* multi disk */
369         i = 160; offset = 720*1024 * (disks - 1);
370         break;
371      default:
372         return IMGTOOLERR_UNEXPECTED;
373      }
374
375   stream_seek (image->file_handle, offset, SEEK_SET);
376
377   while (i--)
378      {
379      if (0x1200 != stream_read (image->file_handle, buf, 0x1200) )
380         return IMGTOOLERR_READERROR;
381
382      if (0x1200 != stream_write (destf, buf, 0x1200) )
383         return IMGTOOLERR_WRITEERROR;
384      }
385
386   return 0;
387   }
388
src/mess/tools/imgtool/modules/os9.c
r0r1340
1/****************************************************************************
2
3   os9.c
4
5   CoCo OS-9 disk images
6
7****************************************************************************/
8
9#include <time.h>
10
11#include "imgtool.h"
12#include "formats/coco_dsk.h"
13#include "iflopimg.h"
14
15typedef enum
16{
17   CREATE_NONE,
18   CREATE_FILE,
19   CREATE_DIR
20} creation_policy_t;
21
22typedef struct _os9_diskinfo os9_diskinfo;
23struct _os9_diskinfo
24{
25   UINT32 total_sectors;
26   UINT32 sectors_per_track;
27   UINT32 allocation_bitmap_bytes;
28   UINT32 cluster_size;
29   UINT32 root_dir_lsn;
30   UINT32 owner_id;
31   UINT32 attributes;
32   UINT32 disk_id;
33   UINT32 format_flags;
34   UINT32 bootstrap_lsn;
35   UINT32 bootstrap_size;
36   UINT32 sector_size;
37
38   unsigned int sides : 2;
39   unsigned int double_density : 1;
40   unsigned int double_track : 1;
41   unsigned int quad_track_density : 1;
42   unsigned int octal_track_density : 1;
43
44   char name[33];
45   UINT8 *allocation_bitmap;
46};
47
48
49struct os9_fileinfo
50{
51   unsigned int directory : 1;
52   unsigned int non_sharable : 1;
53   unsigned int public_execute : 1;
54   unsigned int public_write : 1;
55   unsigned int public_read : 1;
56   unsigned int user_execute : 1;
57   unsigned int user_write : 1;
58   unsigned int user_read : 1;
59
60   UINT32 lsn;
61   UINT32 owner_id;
62   UINT32 link_count;
63   UINT32 file_size;
64
65   struct
66   {
67      UINT32 lsn;
68      UINT32 count;
69   } sector_map[48];
70};
71
72
73struct os9_direnum
74{
75   struct os9_fileinfo dir_info;
76   UINT32 index;
77};
78
79
80
81static void pick_string(const void *ptr, size_t offset, size_t length, char *dest)
82{
83   UINT8 b;
84
85   while(length--)
86   {
87      b = ((UINT8 *) ptr)[offset++];
88      *(dest++) = b & 0x7F;
89      if (b & 0x80)
90         length = 0;
91   }
92   *dest = '\0';
93}
94
95
96
97static void place_string(void *ptr, size_t offset, size_t length, const char *s)
98{
99   size_t i;
100   UINT8 b;
101   UINT8 *bptr;
102
103   bptr = (UINT8 *) ptr;
104   bptr += offset;
105
106   bptr[0] = 0x80;
107
108   for (i = 0; s[i] && (i < length); i++)
109   {
110      b = ((UINT8) s[i]) & 0x7F;
111      if (s[i+1] == '\0')
112         b |= 0x80;
113      bptr[i] = b;
114   }
115}
116
117
118
119static os9_diskinfo *os9_get_diskinfo(imgtool_image *image)
120{
121   return (os9_diskinfo *) imgtool_floppy_extrabytes(image);
122}
123
124
125
126static struct os9_direnum *os9_get_dirinfo(imgtool_directory *directory)
127{
128   return (struct os9_direnum *) imgtool_directory_extrabytes(directory);
129}
130
131
132
133static imgtoolerr_t os9_locate_lsn(imgtool_image *image, UINT32 lsn, UINT32 *head, UINT32 *track, UINT32 *sector)
134{
135   const os9_diskinfo *disk_info;
136
137   disk_info = os9_get_diskinfo(image);
138   if (lsn > disk_info->total_sectors)
139      return IMGTOOLERR_CORRUPTIMAGE;
140
141   *track = lsn / (disk_info->sectors_per_track * disk_info->sides);
142   *head = (lsn / disk_info->sectors_per_track) % disk_info->sides;
143   *sector = (lsn % disk_info->sectors_per_track) + 1;
144   return IMGTOOLERR_SUCCESS;
145}
146
147
148
149static imgtoolerr_t os9_read_lsn(imgtool_image *img, UINT32 lsn, int offset, void *buffer, size_t buffer_len)
150{
151   imgtoolerr_t err;
152   floperr_t ferr;
153   UINT32 head, track, sector;
154
155   err = os9_locate_lsn(img, lsn, &head, &track, &sector);
156   if (err)
157      return err;
158
159   ferr = floppy_read_sector(imgtool_floppy(img), head, track, sector, offset, buffer, buffer_len);
160   if (ferr)
161      return imgtool_floppy_error(ferr);
162
163   return IMGTOOLERR_SUCCESS;
164}
165
166
167
168static imgtoolerr_t os9_write_lsn(imgtool_image *img, UINT32 lsn, int offset, const void *buffer, size_t buffer_len)
169{
170   imgtoolerr_t err;
171   floperr_t ferr;
172   UINT32 head, track, sector;
173
174   err = os9_locate_lsn(img, lsn, &head, &track, &sector);
175   if (err)
176      return err;
177
178   ferr = floppy_write_sector(imgtool_floppy(img), head, track, sector, offset, buffer, buffer_len);
179   if (ferr)
180      return imgtool_floppy_error(ferr);
181
182   return IMGTOOLERR_SUCCESS;
183}
184
185
186
187static UINT32 os9_lookup_lsn(imgtool_image *img,
188   const struct os9_fileinfo *file_info, UINT32 *index)
189{
190   int i;
191   UINT32 lsn;
192   const os9_diskinfo *disk_info;
193
194   disk_info = os9_get_diskinfo(img);
195   lsn = *index / disk_info->sector_size;
196
197   i = 0;
198   while(lsn >= file_info->sector_map[i].count)
199      lsn -= file_info->sector_map[i++].count;
200
201   lsn = file_info->sector_map[i].lsn + lsn;
202   *index %= disk_info->sector_size;
203   return lsn;
204}
205
206
207
208static int os9_interpret_dirent(void *entry, char **filename, UINT32 *lsn, int *corrupt)
209{
210   int i;
211   char *entry_b = (char *) entry;
212
213   *filename = NULL;
214   *lsn = 0;
215   if (corrupt)
216      *corrupt = FALSE;
217
218   if (entry_b[28] != '\0')
219   {
220      if (corrupt)
221         *corrupt = TRUE;
222   }
223
224   for (i = 0; (i < 28) && !(entry_b[i] & 0x80); i++)
225      ;
226   entry_b[i] &= 0x7F;
227   entry_b[i+1] = '\0';
228
229   *lsn = pick_integer_be(entry, 29, 3);
230   if (strcmp(entry_b, ".") && strcmp(entry_b, ".."))
231      *filename = entry_b;
232   return *filename != NULL;
233}
234
235
236
237/*-------------------------------------------------
238    os9_decode_file_header - reads a file/directory
239   entry from an LSN, and decodes it
240-------------------------------------------------*/
241
242static imgtoolerr_t os9_decode_file_header(imgtool_image *image,
243   int lsn, struct os9_fileinfo *info)
244{
245   imgtoolerr_t err;
246   UINT32 attributes, count;
247   int max_entries, i;
248   const os9_diskinfo *disk_info;
249   UINT8 header[256];
250
251   disk_info = os9_get_diskinfo(image);
252
253   err = os9_read_lsn(image, lsn, 0, header, sizeof(header));
254   if (err)
255      return err;
256
257   info->lsn            = lsn;
258   attributes            = pick_integer_be(header, 0, 1);
259   info->owner_id         = pick_integer_be(header, 1, 2);
260   info->link_count      = pick_integer_be(header, 8, 1);
261   info->file_size         = pick_integer_be(header, 9, 4);
262   info->directory         = (attributes & 0x80) ? 1 : 0;
263   info->non_sharable      = (attributes & 0x40) ? 1 : 0;
264   info->public_execute   = (attributes & 0x20) ? 1 : 0;
265   info->public_write      = (attributes & 0x10) ? 1 : 0;
266   info->public_read      = (attributes & 0x08) ? 1 : 0;
267   info->user_execute      = (attributes & 0x04) ? 1 : 0;
268   info->user_write      = (attributes & 0x02) ? 1 : 0;
269   info->user_read         = (attributes & 0x01) ? 1 : 0;
270
271   if (info->directory && (info->file_size % 32 != 0))
272      return IMGTOOLERR_CORRUPTIMAGE;
273
274   /* read all sector map entries */
275   max_entries = (disk_info->sector_size - 16) / 5;
276   max_entries = MIN(max_entries, sizeof(info->sector_map) / sizeof(info->sector_map[0]) - 1);
277   for (i = 0; i < max_entries; i++)
278   {
279      lsn = pick_integer_be(header, 16 + (i * 5) + 0, 3);
280      count = pick_integer_be(header, 16 + (i * 5) + 3, 2);
281      if (count <= 0)
282         break;
283
284      info->sector_map[i].lsn = lsn;
285      info->sector_map[i].count = count;
286   }
287   info->sector_map[i].lsn = 0;
288   info->sector_map[i].count = 0;
289   return IMGTOOLERR_SUCCESS;
290}
291
292
293
294static imgtoolerr_t os9_allocate_lsn(imgtool_image *image, UINT32 *lsn)
295{
296   UINT32 i;
297   os9_diskinfo *disk_info;
298   UINT8 b, mask;
299
300   disk_info = os9_get_diskinfo(image);
301
302   for (i = 0; i < disk_info->total_sectors; i++)
303   {
304      b = disk_info->allocation_bitmap[i / 8];
305      mask = 1 << (7 - (i % 8));
306
307      if ((b & mask) == 0)
308      {
309         disk_info->allocation_bitmap[i / 8] |= mask;
310         *lsn = i;
311         return os9_write_lsn(image, 1, 0, disk_info->allocation_bitmap, disk_info->allocation_bitmap_bytes);
312      }
313   }
314   return IMGTOOLERR_NOSPACE;
315}
316
317
318
319static imgtoolerr_t os9_deallocate_lsn(imgtool_image *image, UINT32 lsn)
320{
321   UINT8 mask;
322   os9_diskinfo *disk_info;
323
324   disk_info = os9_get_diskinfo(image);
325   mask = 1 << (7 - (lsn % 8));
326   disk_info->allocation_bitmap[lsn / 8] &= ~mask;
327   return os9_write_lsn(image, 1, 0, disk_info->allocation_bitmap, disk_info->allocation_bitmap_bytes);
328}
329
330
331
332static UINT32 os9_get_free_lsns(imgtool_image *image)
333{
334   const os9_diskinfo *disk_info;
335   UINT32 i, free_lsns;
336   UINT8 b;
337
338   disk_info = os9_get_diskinfo(image);
339   free_lsns = 0;
340
341   for (i = 0; i < disk_info->total_sectors; i++)
342   {
343      b = disk_info->allocation_bitmap[i / 8];
344      b >>= (7 - (i % 8));
345      free_lsns += ~b & 1;
346   }
347
348   return free_lsns;
349}
350
351   
352
353static imgtoolerr_t os9_corrupt_file_error(const struct os9_fileinfo *file_info)
354{
355   imgtoolerr_t err;
356   if (file_info->directory)
357      err = IMGTOOLERR_CORRUPTDIR;
358   else
359      err = IMGTOOLERR_CORRUPTFILE;
360   return err;
361}
362
363
364
365static imgtoolerr_t os9_set_file_size(imgtool_image *image,
366   struct os9_fileinfo *file_info, UINT32 new_size)
367{
368   imgtoolerr_t err;
369   const os9_diskinfo *disk_info;
370   UINT32 new_lsn_count, current_lsn_count;
371   UINT32 free_lsns, lsn, i;
372   int sector_map_length = -1;
373   UINT8 header[256];
374
375   /* easy way out? */
376   if (file_info->file_size == new_size)
377      return IMGTOOLERR_SUCCESS;
378
379   disk_info = os9_get_diskinfo(image);
380
381   free_lsns = os9_get_free_lsns(image);
382   current_lsn_count = (file_info->file_size + disk_info->sector_size - 1) / disk_info->sector_size;
383   new_lsn_count = (new_size + disk_info->sector_size - 1) / disk_info->sector_size;
384
385   /* check to see if the file is growing and we do not have enough space */
386   if ((new_lsn_count > current_lsn_count) && (new_lsn_count - current_lsn_count > free_lsns))
387      return IMGTOOLERR_NOSPACE;
388
389   if (current_lsn_count != new_lsn_count)
390   {
391      /* first find out the size of our sector map */
392      sector_map_length = 0;
393      lsn = 0;
394      while((lsn < current_lsn_count) && (sector_map_length < sizeof(file_info->sector_map) / sizeof(file_info->sector_map[0])))
395      {
396         if (file_info->sector_map[sector_map_length].count == 0)
397            return os9_corrupt_file_error(file_info);
398
399         lsn += file_info->sector_map[sector_map_length].count;
400         sector_map_length++;
401      }
402
403      /* keep in mind that the sector_map might not parallel our expected
404       * current LSN count; we should tolerate this abnormality */
405      current_lsn_count = lsn;
406
407      while(current_lsn_count > new_lsn_count)
408      {
409         /* shrink this file */
410         lsn = file_info->sector_map[sector_map_length - 1].lsn +
411            file_info->sector_map[sector_map_length - 1].count - 1;
412
413         err = os9_deallocate_lsn(image, lsn);
414         if (err)
415            return err;
416
417         file_info->sector_map[sector_map_length - 1].count--;
418         while(sector_map_length > 0 && (file_info->sector_map[sector_map_length - 1].count == 0))
419            sector_map_length--;
420         current_lsn_count--;
421      }
422
423      while(current_lsn_count < new_lsn_count)
424      {
425         /* grow this file */
426         err = os9_allocate_lsn(image, &lsn);
427         if (err)
428            return err;
429
430         if ((sector_map_length > 0) && ((file_info->sector_map[sector_map_length - 1].lsn +
431            file_info->sector_map[sector_map_length - 1].count) == lsn))
432         {
433            file_info->sector_map[sector_map_length - 1].count++;
434         }
435         else if (sector_map_length >= sizeof(file_info->sector_map) / sizeof(file_info->sector_map[0]))
436         {
437            return IMGTOOLERR_NOSPACE;
438         }
439         else
440         {
441            file_info->sector_map[sector_map_length].lsn = lsn;
442            file_info->sector_map[sector_map_length].count = 1;
443            sector_map_length++;
444            file_info->sector_map[sector_map_length].lsn = 0;
445            file_info->sector_map[sector_map_length].count = 0;
446         }
447         current_lsn_count++;
448      }
449   }
450
451   /* now lets write back the sector */
452   err = os9_read_lsn(image, file_info->lsn, 0, header, sizeof(header));
453   if (err)
454      return err;
455
456   file_info->file_size = new_size;
457   place_integer_be(header, 9, 4, file_info->file_size);
458
459   /* do we have to write the sector map? */
460   if (sector_map_length >= 0)
461   {
462      for (i = 0; i < MIN(sector_map_length + 1, sizeof(file_info->sector_map) / sizeof(file_info->sector_map[0])); i++)
463      {
464         place_integer_be(header, 16 + (i * 5) + 0, 3, file_info->sector_map[i].lsn);
465         place_integer_be(header, 16 + (i * 5) + 3, 2, file_info->sector_map[i].count);
466      }
467   }
468
469   err = os9_write_lsn(image, file_info->lsn, 0, header, disk_info->sector_size);
470   if (err)
471      return err;
472
473   return IMGTOOLERR_SUCCESS;
474}
475
476
477
478/*-------------------------------------------------
479    os9_lookup_path - walks an OS-9 directory
480   structure to find a file, or optionally, create
481   a file
482-------------------------------------------------*/
483
484static imgtoolerr_t os9_lookup_path(imgtool_image *img, const char *path,
485   creation_policy_t create, struct os9_fileinfo *file_info,
486   UINT32 *parent_lsn, UINT32 *dirent_lsn, UINT32 *dirent_index)
487{
488   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
489   struct os9_fileinfo dir_info;
490   UINT32 index, current_lsn, dir_size;
491   UINT32 entry_index = 0;
492   UINT32 free_entry_index = 0xffffffff;
493   UINT32 entry_lsn = 0;
494   UINT32 allocated_lsn = 0;
495   UINT8 entry[32];
496   UINT8 block[64];
497   char *filename;
498   const os9_diskinfo *disk_info;
499
500   disk_info = os9_get_diskinfo(img);
501   current_lsn = disk_info->root_dir_lsn;
502
503   if (parent_lsn)
504      *parent_lsn = 0;
505
506   /* we have to transverse each path element */
507   while(*path)
508   {
509      if (parent_lsn)
510         *parent_lsn = current_lsn;
511
512      /* decode the directory header of this directory */
513      err = os9_decode_file_header(img, current_lsn, &dir_info);
514      if (err)
515         goto done;
516      dir_size = dir_info.file_size;
517
518      /* sanity check directory */
519      if (!dir_info.directory)
520      {
521         err = (current_lsn == disk_info->root_dir_lsn) ? IMGTOOLERR_CORRUPTIMAGE : IMGTOOLERR_INVALIDPATH;
522         goto done;
523      }
524
525      /* walk the directory */
526      for (index = 0; index < dir_size; index += 32)
527      {
528         entry_index = index;
529         entry_lsn = os9_lookup_lsn(img, &dir_info, &entry_index);
530         
531         err = os9_read_lsn(img, entry_lsn, entry_index, entry, sizeof(entry));
532         if (err)
533            goto done;
534
535         /* remember first free entry found */
536         if( free_entry_index == 0xffffffff )
537         {
538            if( entry[0] == 0 )
539               free_entry_index = index;
540         }
541
542         if (os9_interpret_dirent(entry, &filename, &current_lsn, NULL))
543         {
544            if (!strcmp(path, filename))
545               break;
546         }
547         
548      }
549
550      /* at the end of the file? */
551      if (index >= dir_size)
552      {
553         /* if we're not creating, or we are creating but we have not fully
554          * transversed the directory, error out */
555         if (!create || path[strlen(path) + 1])
556         {
557            err = IMGTOOLERR_PATHNOTFOUND;
558            goto done;
559         }
560
561         /* allocate a new LSN */
562         err = os9_allocate_lsn(img, &allocated_lsn);
563         if (err)
564            goto done;
565         
566         /* write the file */
567         memset(block, 0, sizeof(block));
568         place_integer_be(block, 0, 1, 0x1B | ((create == CREATE_DIR) ? 0x80 : 0x00));
569         err = os9_write_lsn(img, allocated_lsn, 0, block, sizeof(block));
570         if (err)
571            goto done;
572         
573         if( free_entry_index == 0xffffffff )
574         {
575            /* expand the directory to hold the new entry */
576            err = os9_set_file_size(img, &dir_info, dir_size + 32);
577            if (err)
578               goto done;
579         }
580         else
581            /* use first unused entry in directory */
582            dir_size = free_entry_index;
583
584         /* now prepare the directory entry */
585         memset(entry, 0, sizeof(entry));
586         place_string(entry, 0, 28, path);
587         place_integer_be(entry, 29, 3, allocated_lsn);
588
589         /* now write the directory entry */
590         entry_index = dir_size;
591         entry_lsn = os9_lookup_lsn(img, &dir_info, &entry_index);
592         err = os9_write_lsn(img, entry_lsn, entry_index, entry, 32);
593         if (err)
594            goto done;
595
596         /* directory entry append complete; no need to hold this lsn */
597         current_lsn = allocated_lsn;
598         allocated_lsn = 0;
599      }
600      path += strlen(path) + 1;
601   }
602
603   if (file_info)
604   {
605      err = os9_decode_file_header(img, current_lsn, file_info);
606      if (err)
607         goto done;
608   }
609
610   if (dirent_lsn)
611      *dirent_lsn = entry_lsn;
612   if (dirent_index)
613      *dirent_index = entry_index;
614
615done:
616   if (allocated_lsn != 0)
617      os9_deallocate_lsn(img, allocated_lsn);
618   return err;
619}
620
621
622
623static imgtoolerr_t os9_diskimage_open(imgtool_image *image, imgtool_stream *stream)
624{
625   imgtoolerr_t err;
626   floperr_t ferr;
627   os9_diskinfo *info;
628   UINT32 track_size_in_sectors, attributes, i;
629   UINT8 header[256];
630   UINT32 allocation_bitmap_lsns;
631   UINT8 b, mask;
632
633   info = os9_get_diskinfo(image);
634
635   ferr = floppy_read_sector(imgtool_floppy(image), 0, 0, 1, 0, header, sizeof(header));
636   if (ferr)
637      return imgtool_floppy_error(ferr);
638
639   info->total_sectors            = pick_integer_be(header,   0, 3);
640   track_size_in_sectors         = pick_integer_be(header,   3, 1);
641   info->allocation_bitmap_bytes   = pick_integer_be(header,   4, 2);
642   info->cluster_size            = pick_integer_be(header,   6, 2);
643   info->root_dir_lsn            = pick_integer_be(header,   8, 3);
644   info->owner_id               = pick_integer_be(header,  11, 2);
645   attributes                  = pick_integer_be(header,  13, 1);
646   info->disk_id               = pick_integer_be(header,  14, 2);
647   info->format_flags            = pick_integer_be(header,  16, 1);
648   info->sectors_per_track         = pick_integer_be(header,  17, 2);
649   info->bootstrap_lsn            = pick_integer_be(header,  21, 3);
650   info->bootstrap_size         = pick_integer_be(header,  24, 2);
651   info->sector_size            = pick_integer_be(header, 104, 2);
652
653   info->sides               = (info->format_flags & 0x01) ? 2 : 1;
654   info->double_density      = (info->format_flags & 0x02) ? 1 : 0;
655   info->double_track         = (info->format_flags & 0x04) ? 1 : 0;
656   info->quad_track_density   = (info->format_flags & 0x08) ? 1 : 0;
657   info->octal_track_density   = (info->format_flags & 0x10) ? 1 : 0;
658
659   pick_string(header, 31, 32, info->name);
660
661   if (info->sector_size == 0)
662      info->sector_size = 256;
663
664   /* does the root directory and allocation bitmap collide? */
665   allocation_bitmap_lsns = (info->allocation_bitmap_bytes + info->sector_size - 1) / info->sector_size;
666   if (1 + allocation_bitmap_lsns > info->root_dir_lsn)
667      return IMGTOOLERR_CORRUPTIMAGE;
668
669   /* is the allocation bitmap too big? */
670   info->allocation_bitmap = imgtool_image_malloc(image, info->allocation_bitmap_bytes);
671   if (!info->allocation_bitmap)
672      return IMGTOOLERR_OUTOFMEMORY;
673   memset(info->allocation_bitmap, 0, info->allocation_bitmap_bytes);
674
675   /* sectors per track and track size dont jive? */
676   if (info->sectors_per_track != track_size_in_sectors)
677      return IMGTOOLERR_CORRUPTIMAGE;
678
679   /* zero sectors per track? */
680   if (info->sectors_per_track == 0)
681      return IMGTOOLERR_CORRUPTIMAGE;
682
683   /* do we have an odd number of sectors? */
684   if (info->total_sectors % info->sectors_per_track)
685      return IMGTOOLERR_CORRUPTIMAGE;
686
687   /* read the allocation bitmap */
688   for (i = 0; i < allocation_bitmap_lsns; i++)
689   {
690      err = os9_read_lsn(image, 1 + i, 0, &info->allocation_bitmap[i * info->sector_size],
691         MIN(info->allocation_bitmap_bytes - (i * info->sector_size), info->sector_size));
692      if (err)
693         return err;
694   }
695
696   /* check to make sure that the allocation bitmap and root sector are reserved */
697   for (i = 0; i <= allocation_bitmap_lsns; i++)
698   {
699      b = info->allocation_bitmap[i / 8];
700      mask = 1 << (7 - (i % 8));
701      if ((b & mask) == 0)
702         return IMGTOOLERR_CORRUPTIMAGE;
703   }
704
705   return IMGTOOLERR_SUCCESS;
706}
707
708
709
710static imgtoolerr_t os9_diskimage_create(imgtool_image *img, imgtool_stream *stream, option_resolution *opts)
711{
712   imgtoolerr_t err;
713   UINT8 *header;
714   UINT32 heads, tracks, sectors, sector_bytes, first_sector_id;
715   UINT32 cluster_size, owner_id;
716   UINT32 allocation_bitmap_bits, allocation_bitmap_lsns;
717   UINT32 attributes, format_flags, disk_id;
718   UINT32 i;
719   INT32 total_allocated_sectors;
720   const char *title;
721   time_t t;
722   struct tm *ltime;
723
724   time(&t);
725   ltime = localtime(&t);
726
727   heads = option_resolution_lookup_int(opts, 'H');
728   tracks = option_resolution_lookup_int(opts, 'T');
729   sectors = option_resolution_lookup_int(opts, 'S');
730   sector_bytes = option_resolution_lookup_int(opts, 'L');
731   first_sector_id = option_resolution_lookup_int(opts, 'F');
732   title = "";
733
734   header = malloc(sector_bytes);
735   if (!header)
736   {
737      err = IMGTOOLERR_OUTOFMEMORY;
738      goto done;
739   }
740
741   if (sector_bytes > 256)
742      sector_bytes = 256;
743   cluster_size = 1;
744   owner_id = 1;
745   disk_id = 1;
746   attributes = 0;
747   allocation_bitmap_bits = heads * tracks * sectors / cluster_size;
748   allocation_bitmap_lsns = (allocation_bitmap_bits / 8 + sector_bytes - 1) / sector_bytes;
749   format_flags = ((heads > 1) ? 0x01 : 0x00) | ((tracks > 40) ? 0x02 : 0x00);
750
751   memset(header, 0, sector_bytes);
752   place_integer_be(header,   0,  3, heads * tracks * sectors);
753   place_integer_be(header,   3,  1, sectors);
754   place_integer_be(header,   4,  2, (allocation_bitmap_bits + 7) / 8);
755   place_integer_be(header,   6,  2, cluster_size);
756   place_integer_be(header,   8,  3, 1 + allocation_bitmap_lsns);
757   place_integer_be(header,  11,  2, owner_id);
758   place_integer_be(header,  13,  1, attributes);
759   place_integer_be(header,  14,  2, disk_id);
760   place_integer_be(header,  16,  1, format_flags);
761   place_integer_be(header,  17,  2, sectors);
762   place_string(header,   31, 32, title);
763   place_integer_be(header, 103, 2, sector_bytes / 256);
764   
765   /* path descriptor options */
766   place_integer_be(header, 0x3f+0x00, 1, 1); /* device class */
767   place_integer_be(header, 0x3f+0x01, 1, 1); /* drive number */
768   place_integer_be(header, 0x3f+0x03, 1, 0x20); /* device type */
769   place_integer_be(header, 0x3f+0x04, 1, 1); /* density capability */
770   place_integer_be(header, 0x3f+0x05, 2, tracks); /* number of tracks */
771   place_integer_be(header, 0x3f+0x07, 1, heads); /* number of sides */
772   place_integer_be(header, 0x3f+0x09, 2, sectors); /* sectors per track */
773   place_integer_be(header, 0x3f+0x0b, 2, sectors); /* sectors on track zero */
774   place_integer_be(header, 0x3f+0x0d, 1, 3); /* sector interleave factor */
775   place_integer_be(header, 0x3f+0x0e, 1, 8); /* default sectors per allocation */
776   
777   err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id, 0, header, sector_bytes);
778   if (err)
779      goto done;
780
781   total_allocated_sectors = 1 + allocation_bitmap_lsns + 1 + 7;
782
783   for (i = 0; i < allocation_bitmap_lsns; i++)
784   {
785      memset(header, 0x00, sector_bytes);
786     
787      if (total_allocated_sectors > (8 * 256))
788      {
789         memset(header, 0xff, sector_bytes);
790         total_allocated_sectors -= (8 * 256);
791      }
792      else if (total_allocated_sectors > 1 )
793      {
794         int offset;
795         UINT8 mask;
796           
797         while( total_allocated_sectors >= 0 )
798         {
799            offset = total_allocated_sectors / 8;
800            mask = 1 << (7 - ( total_allocated_sectors % 8 ) );
801
802            header[offset] |= mask;
803            total_allocated_sectors--;
804         }
805      }
806     
807      err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 1 + i, 0, header, sector_bytes);
808      if (err)
809         goto done;
810   }
811
812   memset(header, 0, sector_bytes);
813   header[0x00] = 0xBF;
814   header[0x01] = 0x00;
815   header[0x02] = 0x00;
816   header[0x03] = (UINT8) ltime->tm_year;
817   header[0x04] = (UINT8) ltime->tm_mon + 1;
818   header[0x05] = (UINT8) ltime->tm_mday;
819   header[0x06] = (UINT8) ltime->tm_hour;
820   header[0x07] = (UINT8) ltime->tm_min;
821   header[0x08] = 0x02;
822   header[0x09] = 0x00;
823   header[0x0A] = 0x00;
824   header[0x0B] = 0x00;
825   header[0x0C] = 0x40;
826   header[0x0D] = (UINT8) (ltime->tm_year % 100);
827   header[0x0E] = (UINT8) ltime->tm_mon;
828   header[0x0F] = (UINT8) ltime->tm_mday;
829   place_integer_be(header, 0x10, 3, 1 + allocation_bitmap_lsns + 1);
830   place_integer_be(header, 0x13, 2, 8);
831
832   err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 1 + allocation_bitmap_lsns, 0, header, sector_bytes);
833   if (err)
834      goto done;
835
836   memset(header, 0, sector_bytes);
837   header[0x00] = 0x2E;
838   header[0x01] = 0xAE;
839   header[0x1F] = 1 + allocation_bitmap_lsns;
840   header[0x20] = 0xAE;
841   header[0x3F] = 1 + allocation_bitmap_lsns;
842   err = floppy_write_sector(imgtool_floppy(img), 0, 0, first_sector_id + 2 + allocation_bitmap_lsns, 0, header, sector_bytes);
843   if (err)
844      goto done;
845
846done:
847   if (header)
848      free(header);
849   return err;
850}
851
852
853
854static imgtoolerr_t os9_diskimage_beginenum(imgtool_directory *enumeration, const char *path)
855{
856   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
857   struct os9_direnum *os9enum;
858   imgtool_image *image;
859
860   image = imgtool_directory_image(enumeration);
861   os9enum = os9_get_dirinfo(enumeration);
862
863   err = os9_lookup_path(image, path, CREATE_NONE, &os9enum->dir_info, NULL, NULL, NULL);
864   if (err)
865      goto done;
866
867   /* this had better be a directory */
868   if (!os9enum->dir_info.directory)
869   {
870      err = IMGTOOLERR_CORRUPTIMAGE;
871      goto done;
872   }
873
874done:
875   return err;
876}
877
878
879
880static imgtoolerr_t os9_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
881{
882   struct os9_direnum *os9enum;
883   UINT32 lsn, index;
884   imgtoolerr_t err;
885   UINT8 dir_entry[32];
886   char filename[29];
887   struct os9_fileinfo file_info;
888   imgtool_image *image;
889
890   image = imgtool_directory_image(enumeration);
891   os9enum = os9_get_dirinfo(enumeration);
892
893   do
894   {
895      /* check for EOF */
896      if (os9enum->index >= os9enum->dir_info.file_size)
897      {
898         ent->eof = 1;
899         return IMGTOOLERR_SUCCESS;
900      }
901
902      /* locate the LSN and offset for this directory entry */
903      index = os9enum->index;
904      lsn = os9_lookup_lsn(image, &os9enum->dir_info, &index);
905
906      /* read the directory entry out of the lSN */
907      err = os9_read_lsn(image, lsn, index, dir_entry, sizeof(dir_entry));
908      if (err)
909         return err;
910
911      if (dir_entry[0])
912      {
913         /* read the file or directory name */
914         pick_string(dir_entry, 0, 28, filename);
915
916         /* we have certain expectations of the directory contents; the
917          * first directory entry should be "..", the second ".", and
918          * subsequent entries should never be "." or ".." */
919         switch(os9enum->index)
920         {
921            case 0:
922               if (strcmp(filename, ".."))
923                  imgtool_warn("First entry in directory should be \"..\" and not \"%s\"", filename);
924               break;
925
926            case 32:
927               if (strcmp(filename, "."))
928                  imgtool_warn("Second entry in directory should be \".\" and not \"%s\"", filename);
929               break;
930
931            default:
932               if (!strcmp(filename, ".") || !strcmp(filename, ".."))
933                  imgtool_warn("Directory entry %d should not be \"%s\"", index / 32, filename);
934               break;
935         }
936
937         /* if the filename is ".", the file should point to the current directory */
938         if (!strcmp(filename, ".") && (pick_integer_be(dir_entry, 29, 3) != os9enum->dir_info.lsn))
939         {
940            imgtool_warn("Directory \".\" does not point back to same directory");
941         }
942      }
943      else
944      {
945         /* no more directory entries */
946         filename[0] = '\0';
947      }
948
949      /* move on to the next directory entry */
950      os9enum->index += 32;
951   }
952   while(!filename[0] || !strcmp(filename, ".") || !strcmp(filename, ".."));
953
954   /* read file attributes */
955   lsn = pick_integer_be(dir_entry, 29, 3);
956   err = os9_decode_file_header(imgtool_directory_image(enumeration), lsn, &file_info);
957   if (err)
958      return err;
959
960   /* fill out imgtool_dirent structure */
961   snprintf(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), "%s", filename);
962   snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%c%c%c%c%c%c%c%c",
963      file_info.directory      ? 'd' : '-',
964      file_info.non_sharable   ? 's' : '-',
965      file_info.public_execute ? 'x' : '-',
966      file_info.public_write   ? 'w' : '-',
967      file_info.public_read    ? 'r' : '-',
968      file_info.user_execute   ? 'x' : '-',
969      file_info.user_write     ? 'w' : '-',
970      file_info.user_read      ? 'r' : '-');
971
972   ent->directory = file_info.directory;
973   ent->corrupt = (dir_entry[28] != 0);
974   ent->filesize = file_info.file_size;
975   return IMGTOOLERR_SUCCESS;
976}
977
978
979
980static imgtoolerr_t os9_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
981{
982   imgtool_image *image = imgtool_partition_image(partition);
983   const os9_diskinfo *disk_info;
984   UINT32 free_lsns;
985
986   disk_info = os9_get_diskinfo(image);
987   free_lsns = os9_get_free_lsns(image);
988
989   *size = free_lsns * disk_info->sector_size;
990   return IMGTOOLERR_SUCCESS;
991}
992
993
994
995static imgtoolerr_t os9_diskimage_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
996{
997   imgtoolerr_t err;
998   imgtool_image *img = imgtool_partition_image(partition);
999   const os9_diskinfo *disk_info;
1000   struct os9_fileinfo file_info;
1001   UINT8 buffer[256];
1002   int i, j;
1003   UINT32 file_size;
1004   UINT32 used_size;
1005
1006   disk_info = os9_get_diskinfo(img);
1007
1008   err = os9_lookup_path(img, filename, CREATE_NONE, &file_info, NULL, NULL, NULL);
1009   if (err)
1010      return err;
1011   if (file_info.directory)
1012      return IMGTOOLERR_FILENOTFOUND;
1013   file_size = file_info.file_size;
1014
1015   for (i = 0; file_info.sector_map[i].count > 0; i++)
1016   {
1017      for (j = 0; j < file_info.sector_map[i].count; j++)
1018      {
1019         used_size = MIN(file_size, disk_info->sector_size);
1020         err = os9_read_lsn(img, file_info.sector_map[i].lsn + j, 0,
1021            buffer, used_size);
1022         if (err)
1023            return err;
1024         stream_write(destf, buffer, used_size);
1025         file_size -= used_size;
1026      }
1027   }
1028   return IMGTOOLERR_SUCCESS;
1029}
1030
1031
1032
1033static imgtoolerr_t os9_diskimage_writefile(imgtool_partition *partition, const char *path, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
1034{
1035   imgtoolerr_t err;
1036   imgtool_image *image = imgtool_partition_image(partition);
1037   struct os9_fileinfo file_info;
1038   size_t write_size;
1039   void *buf = NULL;
1040   int i = -1;
1041   UINT32 lsn = 0;
1042   UINT32 count = 0;
1043   UINT32 sz;
1044   const os9_diskinfo *disk_info;
1045
1046   disk_info = os9_get_diskinfo(image);
1047
1048   buf = malloc(disk_info->sector_size);
1049   if (!buf)
1050   {
1051      err = IMGTOOLERR_OUTOFMEMORY;
1052      goto done;
1053   }
1054
1055   err = os9_lookup_path(image, path, CREATE_FILE, &file_info, NULL, NULL, NULL);
1056   if (err)
1057      goto done;
1058
1059   sz = (UINT32) stream_size(sourcef);
1060
1061   err = os9_set_file_size(image, &file_info, sz);
1062   if (err)
1063      goto done;
1064
1065   while(sz > 0)
1066   {
1067      write_size = (size_t) MIN(sz, (UINT64) disk_info->sector_size);
1068
1069      stream_read(sourcef, buf, write_size);
1070
1071      while(count == 0)
1072      {
1073         i++;
1074         lsn = file_info.sector_map[i].lsn;
1075         count = file_info.sector_map[i].count;
1076      }
1077
1078      err = os9_write_lsn(image, lsn, 0, buf, write_size);
1079      if (err)
1080         goto done;
1081
1082      lsn++;
1083      count--;
1084      sz -= write_size;
1085   }
1086
1087done:
1088   if (buf)
1089      free(buf);
1090   return err;
1091}
1092
1093
1094
1095static imgtoolerr_t os9_diskimage_delete(imgtool_partition *partition, const char *path,
1096   unsigned int delete_directory)
1097{
1098   imgtoolerr_t err;
1099   imgtool_image *image = imgtool_partition_image(partition);
1100   const os9_diskinfo *disk_info;
1101   struct os9_fileinfo file_info;
1102   UINT32 dirent_lsn, dirent_index;
1103   UINT32 entry_lsn, entry_index;
1104   UINT32 i, j, lsn;
1105   UINT8 b;
1106
1107   disk_info = os9_get_diskinfo(image);
1108
1109   err = os9_lookup_path(image, path, CREATE_NONE, &file_info, NULL, &dirent_lsn, &dirent_index);
1110   if (err)
1111      return err;
1112   if (file_info.directory != delete_directory)
1113      return IMGTOOLERR_FILENOTFOUND;
1114
1115   /* make sure that if we are deleting a directory, it is empty */
1116   if (delete_directory)
1117   {
1118      for (i = 64; i < file_info.file_size; i += 32)
1119      {
1120         entry_index = i;
1121         entry_lsn = os9_lookup_lsn(image, &file_info, &entry_index);
1122
1123         err = os9_read_lsn(image, entry_lsn, entry_index, &b, 1);
1124         if (err)
1125            return err;
1126
1127         /* this had better be a deleted file, if not we can't delete */
1128         if (b != 0)
1129            return IMGTOOLERR_DIRNOTEMPTY;
1130      }
1131   }
1132
1133   /* zero out the file entry */
1134   b = '\0';
1135   err = os9_write_lsn(image, dirent_lsn, dirent_index, &b, 1);
1136   if (err)
1137      return err;
1138
1139   /* get the link count */
1140   err = os9_read_lsn(image, file_info.lsn, 8, &b, 1);
1141   if (err)
1142      return err;
1143
1144   if (b > 0)
1145      b--;
1146   if (b > 0)
1147   {
1148      /* link count is greater than zero */
1149      err = os9_write_lsn(image, file_info.lsn, 8, &b, 1);
1150      if (err)
1151         return err;
1152   }
1153   else
1154   {
1155      /* no more links; outright delete the file */
1156      err = os9_deallocate_lsn(image, file_info.lsn);
1157      if (err)
1158         return err;
1159
1160      for (i = 0; (i < sizeof(file_info.sector_map) / sizeof(file_info.sector_map[0])) && file_info.sector_map[i].count; i++)
1161      {
1162         lsn = file_info.sector_map[i].lsn;
1163         for (j = 0;  j < file_info.sector_map[i].count; j++)
1164         {
1165            err = os9_deallocate_lsn(image, lsn + j);
1166            if (err)
1167               return err;
1168         }
1169      }
1170   }
1171
1172   return IMGTOOLERR_SUCCESS;
1173}
1174
1175
1176
1177static imgtoolerr_t os9_diskimage_deletefile(imgtool_partition *partition, const char *path)
1178{
1179   return os9_diskimage_delete(partition, path, 0);
1180}
1181
1182
1183
1184static imgtoolerr_t os9_diskimage_createdir(imgtool_partition *partition, const char *path)
1185{
1186   imgtoolerr_t err;
1187   imgtool_image *image = imgtool_partition_image(partition);
1188   struct os9_fileinfo file_info;
1189   UINT8 dir_data[64];
1190   UINT32 parent_lsn;
1191
1192   err = os9_lookup_path(image, path, CREATE_DIR, &file_info, &parent_lsn, NULL, NULL);
1193   if (err)
1194      goto done;
1195
1196   err = os9_set_file_size(image, &file_info, 64);
1197   if (err)
1198      goto done;
1199
1200   /* create intial directories */
1201   memset(dir_data, 0, sizeof(dir_data));
1202   place_string(dir_data,   0, 32, "..");
1203   place_integer_be(dir_data, 29,  3, parent_lsn);
1204   place_string(dir_data,  32, 32, ".");
1205   place_integer_be(dir_data, 61,  3, file_info.lsn);
1206
1207   err = os9_write_lsn(image, file_info.sector_map[0].lsn, 0, dir_data, sizeof(dir_data));
1208   if (err)
1209      goto done;
1210
1211done:
1212   return err;
1213}
1214
1215
1216
1217static imgtoolerr_t os9_diskimage_deletedir(imgtool_partition *partition, const char *path)
1218{
1219   return os9_diskimage_delete(partition, path, 1);
1220}
1221
1222
1223
1224void os9_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
1225{
1226   switch(state)
1227   {
1228      /* --- the following bits of info are returned as 64-bit signed integers --- */
1229      case IMGTOOLINFO_INT_INITIAL_PATH_SEPARATOR:      info->i = 1; break;
1230      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
1231      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(os9_diskinfo); break;
1232      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(struct os9_direnum); break;
1233      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = '/'; break;
1234
1235      /* --- the following bits of info are returned as NULL-terminated strings --- */
1236      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "os9"); break;
1237      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "OS-9 format"); break;
1238      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
1239      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
1240
1241      /* --- the following bits of info are returned as pointers to data or functions --- */
1242      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
1243      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = os9_diskimage_create; break;
1244      case IMGTOOLINFO_PTR_FLOPPY_OPEN:               info->open = os9_diskimage_open; break;
1245      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = os9_diskimage_beginenum; break;
1246      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = os9_diskimage_nextenum; break;
1247      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = os9_diskimage_freespace; break;
1248      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = os9_diskimage_readfile; break;
1249      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = os9_diskimage_writefile; break;
1250      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = os9_diskimage_deletefile; break;
1251      case IMGTOOLINFO_PTR_CREATE_DIR:               info->create_dir = os9_diskimage_createdir; break;
1252      case IMGTOOLINFO_PTR_DELETE_DIR:               info->delete_dir = os9_diskimage_deletedir; break;
1253      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_coco; break;
1254   }
1255}
src/mess/tools/imgtool/modules/fat.c
r0r1340
1/****************************************************************************
2
3   fat.c
4
5   PC FAT disk images
6
7*****************************************************************************
8
9  Master boot record format:
10
11  Offset  Length  Description
12  ------  ------  -----------
13       0     446  Boot machine code
14     446      16  Partion #1 info
15     462      16  Partion #2 info
16     478      16  Partion #3 info
17     494      16  Partion #4 info
18    510       2  Magic bytes (0x55 0xAA)
19
20
21  Partition info format:
22
23  Offset  Length  Description
24  ------  ------  -----------
25       0       1  Active byte (0x80=active 0x00=inactive)
26      1       1  Starting head
27      2       1  Starting sector (bits 5-0) and high bits of starting track (bits 6-5)
28      3       1  Low bits of starting track
29      4       1  Partition type:
30                   0x00      Unused
31                  0x?1      FAT12   (0-15 MB)
32                  0x?2      XENIX
33                  0x?4      FAT16   (16-32 MB)
34                  0x?6      FAT16`   (32 MB-2 GB)
35                  0x?7      HPFS or NTFS
36                  0x?A      Boot Manager
37                  0x?B      FAT32   (512 MB-2 TB)
38                  0x?C      FAT32   (512 MB-2 TB LBA)
39                  0x1?      OS/2 Boot manager/Win95 hidden
40                  0xC?      DR-DOS secured partition
41                  0xD?      Multiuser DOS secured partition
42                  0xE?      SpeedStor extended partition
43      5       1  Ending head
44      6       1  Ending sector (bits 5-0) and high bits of ending track (bits 6-5)
45      7       1  Low bits of ending track
46      8       4  Sector index of beginning of partition
47     12       4  Total sectors in partition
48
49
50  Boot sector format:
51
52  Offset  Length  Description
53  ------  ------  -----------
54       0       3  Jump instruction (to skip over header on boot)
55      3       8  OEM Name
56      11       2  Bytes per sector
57     13       1  Sectors per cluster
58     14       2  Reserved sector count (including boot sector)
59     16       1  Number of FATs (file allocation tables)
60     17       2  Number of root directory entries
61     19       2  Total sectors (bits 0-15)
62     21       1  Media descriptor
63     22       2  Sectors per FAT
64     24       2  Sectors per track
65     26       2  Number of heads
66     28       4  Hidden sectors
67     32       4  Total sectors (bits 16-47)
68     36       1  Physical drive number
69      37       1  Current head
70     38       1  Signature
71     39       4  ID
72     43      11  Volume Label
73     54       8  FAT file system type
74     62     448  Boot machine code
75    510       2  Magic bytes (0x55 0xAA)
76
77  For more information:
78   http://support.microsoft.com/kb/q140418/
79
80
81  Directory Entry Format:
82
83  Offset  Length  Description
84  ------  ------  -----------
85       0       8  DOS File Name (padded with spaces)
86      8       3  DOS File Extension (padded with spaces)
87     11       1  File Attributes
88     12       2  Unknown
89     14       4  Time of Creation
90     18       2  Last Access Time
91     20       2  EA-Index (OS/2 stuff)
92     22       4  Last Modified Time
93     26       2  First Cluster
94     28       4  File Size
95
96
97  Dates and times are stored in separate words; when together, the time is
98  first and the date is second.
99
100   Time:
101      bits 15-11      Hour
102      bits 10- 5      Minute
103      bits  4- 0      Second / 2
104
105   Date:
106      bits 15- 9      Year - 1980
107      bits  8- 5      Month
108      bits  4- 0      Day
109
110  LFN Entry Format:
111
112  Offset  Length  Description
113  ------  ------  -----------
114       0       1  Sequence Number (bit 6 is set on highest sequence)
115      1      10  Name characters (five UTF-16LE chars)
116     11       1  Attributes (always 0x0F)
117     12       1  Reserved (always 0x00)
118     13       1  Checksum of short filename entry
119     14      12  Name characters (six UTF-16LE chars)
120     26       2  Entry Cluster (always 0x00)
121     28       4  Name characters (two UTF-16LE chars)
122 
123  Valid characters in DOS file names:
124   - Upper case letters A-Z
125   - Numbers 0-9
126   - Space (though there is no way to identify a trailing space)
127   - ! # $ % & ( ) - @ ^ _ ` { } ~
128   - Characters 128-255 (though the code page is indeterminate)
129
130  For more information:
131   http://en.wikipedia.org/wiki/File_Allocation_Table
132
133****************************************************************************/
134
135#include <time.h>
136#include <ctype.h>
137
138#include "imgtool.h"
139#include "unicode.h"
140
141#define FAT_DIRENT_SIZE         32
142#define FAT_SECLEN            512
143
144#define LOG(x)
145
146typedef struct _fat_partition_info fat_partition_info;
147struct _fat_partition_info
148{
149   UINT32 fat_bits;
150   UINT32 sectors_per_cluster;
151   UINT32 cluster_size;
152   UINT32 reserved_sectors;
153   UINT32 fat_count;
154   UINT32 root_entries;
155   UINT32 sectors_per_fat;
156   UINT64 total_sectors;
157   UINT32 total_clusters;
158};
159
160typedef struct _fat_file fat_file;
161struct _fat_file
162{
163   unsigned int root : 1;
164   unsigned int directory : 1;
165   unsigned int eof : 1;
166   UINT32 index;
167   UINT32 filesize;
168   UINT32 first_cluster;
169   UINT32 parent_first_cluster;
170   UINT32 cluster;
171   UINT32 cluster_index;
172   UINT32 dirent_sector_index;
173   UINT32 dirent_sector_offset;
174};
175
176typedef struct _fat_dirent fat_dirent;
177struct _fat_dirent
178{
179   char long_filename[512];
180   char short_filename[13];
181   unsigned int directory : 1;
182   unsigned int eof : 1;
183   UINT32 filesize;
184   UINT32 first_cluster;
185   UINT32 dirent_sector_index;
186   UINT32 dirent_sector_offset;
187   time_t creation_time;
188   time_t lastmodified_time;
189};
190
191typedef struct _fat_freeentry_info fat_freeentry_info;
192struct _fat_freeentry_info
193{
194   UINT32 required_size;
195   UINT32 candidate_position;
196   UINT32 position;
197};
198
199typedef struct _fat_mediatype fat_mediatype;
200struct _fat_mediatype
201{
202   UINT8 media_descriptor;
203   UINT8 heads;
204   UINT8 tracks;
205   UINT8 sectors;
206};
207
208typedef enum
209{
210   CREATE_NONE,
211   CREATE_FILE,
212   CREATE_DIR
213} creation_policy_t;
214
215
216
217static const fat_mediatype known_media[] =
218{
219   { 0xF0, 2, 80, 36 },
220   { 0xF0, 2, 80, 18 },
221   { 0xF9, 2, 80,  9 },
222   { 0xF9, 2, 80, 15 },
223   { 0xFD, 2, 40,  9 },
224   { 0xFF, 2, 40,  8 },
225   { 0xFC, 1, 40,  9 },
226   { 0xFE, 1, 40,  8 },
227   { 0xF8, 0,  0,  0 }
228};
229
230/* boot sector code taken from FreeDOS */
231static const UINT8 boot_sector_code[] =
232{
233   0xfa, 0xfc, 0x31, 0xc0, 0x8e, 0xd8, 0xbd, 0x00, 0x7c, 0xb8, 0xe0, 0x1f,
234   0x8e, 0xc0, 0x89, 0xee, 0x89, 0xef, 0xb9, 0x00, 0x01, 0xf3, 0xa5, 0xea,
235   0x5e, 0x7c, 0xe0, 0x1f, 0x00, 0x00, 0x60, 0x00, 0x8e, 0xd8, 0x8e, 0xd0,
236   0x8d, 0x66, 0xa0, 0xfb, 0x80, 0x7e, 0x24, 0xff, 0x75, 0x03, 0x88, 0x56,
237   0x24, 0xc7, 0x46, 0xc0, 0x10, 0x00, 0xc7, 0x46, 0xc2, 0x01, 0x00, 0x8b,
238   0x76, 0x1c, 0x8b, 0x7e, 0x1e, 0x03, 0x76, 0x0e, 0x83, 0xd7, 0x00, 0x89,
239   0x76, 0xd2, 0x89, 0x7e, 0xd4, 0x8a, 0x46, 0x10, 0x98, 0xf7, 0x66, 0x16,
240   0x01, 0xc6, 0x11, 0xd7, 0x89, 0x76, 0xd6, 0x89, 0x7e, 0xd8, 0x8b, 0x5e,
241   0x0b, 0xb1, 0x05, 0xd3, 0xeb, 0x8b, 0x46, 0x11, 0x31, 0xd2, 0xf7, 0xf3,
242   0x89, 0x46, 0xd0, 0x01, 0xc6, 0x83, 0xd7, 0x00, 0x89, 0x76, 0xda, 0x89,
243   0x7e, 0xdc, 0x8b, 0x46, 0xd6, 0x8b, 0x56, 0xd8, 0x8b, 0x7e, 0xd0, 0xc4,
244   0x5e, 0x5a, 0xe8, 0xac, 0x00, 0xc4, 0x7e, 0x5a, 0xb9, 0x0b, 0x00, 0xbe,
245   0xf1, 0x7d, 0x57, 0xf3, 0xa6, 0x5f, 0x26, 0x8b, 0x45, 0x1a, 0x74, 0x0b,
246   0x83, 0xc7, 0x20, 0x26, 0x80, 0x3d, 0x00, 0x75, 0xe7, 0x72, 0x68, 0x50,
247   0xc4, 0x5e, 0x5a, 0x8b, 0x7e, 0x16, 0x8b, 0x46, 0xd2, 0x8b, 0x56, 0xd4,
248   0xe8, 0x7e, 0x00, 0x58, 0x1e, 0x07, 0x8e, 0x5e, 0x5c, 0xbf, 0x00, 0x20,
249   0xab, 0x89, 0xc6, 0x01, 0xf6, 0x01, 0xc6, 0xd1, 0xee, 0xad, 0x73, 0x04,
250   0xb1, 0x04, 0xd3, 0xe8, 0x80, 0xe4, 0x0f, 0x3d, 0xf8, 0x0f, 0x72, 0xe8,
251   0x31, 0xc0, 0xab, 0x0e, 0x1f, 0xc4, 0x5e, 0x5a, 0xbe, 0x00, 0x20, 0xad,
252   0x09, 0xc0, 0x75, 0x05, 0x88, 0xd3, 0xff, 0x6e, 0x5a, 0x48, 0x48, 0x8b,
253   0x7e, 0x0d, 0x81, 0xe7, 0xff, 0x00, 0xf7, 0xe7, 0x03, 0x46, 0xda, 0x13,
254   0x56, 0xdc, 0xe8, 0x34, 0x00, 0xeb, 0xe0, 0x5e, 0xac, 0x56, 0xb4, 0x0e,
255   0xcd, 0x10, 0x3c, 0x2e, 0x75, 0xf5, 0xc3, 0xe8, 0xf1, 0xff, 0x45, 0x72,
256   0x72, 0x6f, 0x72, 0x21, 0x20, 0x48, 0x69, 0x74, 0x20, 0x61, 0x20, 0x6b,
257   0x65, 0x79, 0x20, 0x74, 0x6f, 0x20, 0x72, 0x65, 0x62, 0x6f, 0x6f, 0x74,
258   0x2e, 0x30, 0xe4, 0xcd, 0x13, 0xcd, 0x16, 0xcd, 0x19, 0x56, 0x89, 0x46,
259   0xc8, 0x89, 0x56, 0xca, 0x8c, 0x46, 0xc6, 0x89, 0x5e, 0xc4, 0xe8, 0xbe,
260   0xff, 0x2e, 0xb4, 0x41, 0xbb, 0xaa, 0x55, 0x8a, 0x56, 0x24, 0x84, 0xd2,
261   0x74, 0x19, 0xcd, 0x13, 0x72, 0x15, 0xd1, 0xe9, 0x81, 0xdb, 0x54, 0xaa,
262   0x75, 0x0d, 0x8d, 0x76, 0xc0, 0x89, 0x5e, 0xcc, 0x89, 0x5e, 0xce, 0xb4,
263   0x42, 0xeb, 0x26, 0x8b, 0x4e, 0xc8, 0x8b, 0x56, 0xca, 0x8a, 0x46, 0x18,
264   0xf6, 0x66, 0x1a, 0x91, 0xf7, 0xf1, 0x92, 0xf6, 0x76, 0x18, 0x89, 0xd1,
265   0x88, 0xc6, 0x86, 0xe9, 0xd0, 0xc9, 0xd0, 0xc9, 0x08, 0xe1, 0x41, 0xc4,
266   0x5e, 0xc4, 0xb8, 0x01, 0x02, 0x8a, 0x56, 0x24, 0xcd, 0x13, 0x0f, 0x82,
267   0x75, 0xff, 0x8b, 0x46, 0x0b, 0xf6, 0x76, 0xc0, 0x01, 0x46, 0xc6, 0x83,
268   0x46, 0xc8, 0x01, 0x83, 0x56, 0xca, 0x00, 0x4f, 0x75, 0x98, 0x8e, 0x46,
269   0xc6, 0x5e, 0xc3, 0x4d, 0x45, 0x54, 0x41, 0x4b, 0x45, 0x52, 0x4e, 0x53,
270   0x59, 0x53, 0x00, 0x00, 0x55, 0xaa
271};
272
273static const char fat8_string[8]  = { 'F', 'A', 'T', ' ', ' ', ' ', ' ', ' ' };
274static const char fat12_string[8] = { 'F', 'A', 'T', '1', '2', ' ', ' ', ' ' };
275static const char fat16_string[8] = { 'F', 'A', 'T', '1', '6', ' ', ' ', ' ' };
276static const char fat32_string[8] = { 'F', 'A', 'T', '3', '2', ' ', ' ', ' ' };
277
278
279
280static fat_partition_info *fat_get_partition_info(imgtool_partition *partition)
281{
282   return (fat_partition_info *) imgtool_partition_extra_bytes(partition);
283}
284
285
286
287static imgtoolerr_t fat_read_sector(imgtool_partition *partition, UINT32 sector_index,
288   int offset, void *buffer, size_t buffer_len)
289{
290   const fat_partition_info *disk_info;
291   imgtoolerr_t err;
292   UINT8 data[FAT_SECLEN];
293   UINT32 block_size;
294   size_t len;
295
296   disk_info = fat_get_partition_info(partition);
297
298   /* sanity check */
299   err = imgtool_partition_get_block_size(partition, &block_size);
300   if (err)
301      return err;
302   assert(block_size == sizeof(data));
303
304   while(buffer_len > 0)
305   {
306      err = imgtool_partition_read_block(partition, sector_index++, data);
307      if (err)
308         return err;
309
310      len = MIN(buffer_len, sizeof(data) - offset);
311      memcpy(buffer, data + offset, len);
312
313      buffer = ((UINT8 *) buffer) + len;
314      buffer_len -= len;
315      offset = 0;
316   }
317   return IMGTOOLERR_SUCCESS;
318}
319
320
321
322static imgtoolerr_t fat_write_sector(imgtool_partition *partition, UINT32 sector_index,
323   int offset, const void *buffer, size_t buffer_len)
324{
325   const fat_partition_info *disk_info;
326   imgtoolerr_t err;
327   UINT8 data[FAT_SECLEN];
328   const void *write_data;
329   UINT32 block_size;
330   size_t len;
331
332   disk_info = fat_get_partition_info(partition);
333
334   /* sanity check */
335   err = imgtool_partition_get_block_size(partition, &block_size);
336   if (err)
337      return err;
338   assert(block_size == sizeof(data));
339
340   while(buffer_len > 0)
341   {
342      len = MIN(buffer_len, sizeof(data) - offset);
343
344      if ((offset != 0) || (buffer_len < sizeof(data)))
345      {
346         err = imgtool_partition_read_block(partition, sector_index, data);
347         if (err)
348            return err;
349         memcpy(data + offset, buffer, len);
350         write_data = data;
351      }
352      else
353      {
354         write_data = buffer;
355      }
356
357      err = imgtool_partition_write_block(partition, sector_index++, write_data);
358      if (err)
359         return err;
360
361      buffer = ((UINT8 *) buffer) + len;
362      buffer_len -= len;
363      offset = 0;
364   }
365   return IMGTOOLERR_SUCCESS;
366}
367
368
369#ifdef UNUSED_FUNCTION
370static imgtoolerr_t fat_clear_sector(imgtool_partition *partition, UINT32 sector_index, UINT8 data)
371{
372   char buf[FAT_SECLEN];
373   memset(buf, data, sizeof(buf));
374   return fat_write_sector(partition, sector_index, 0, buf, sizeof(buf));
375}
376#endif
377
378
379static imgtoolerr_t fat_partition_open(imgtool_partition *partition, UINT64 first_block, UINT64 block_count)
380{
381   UINT8 header[FAT_SECLEN];
382   imgtoolerr_t err;
383   fat_partition_info *info;
384   UINT32 fat_bits, total_sectors_l, total_sectors_h, sector_size;
385   UINT64 available_sectors;
386   int has_extended_bios_param_block = TRUE;
387
388   info = fat_get_partition_info(partition);
389
390   /* read the boot/root sector */
391   err = fat_read_sector(partition, 0, 0, header, sizeof(header));
392   if (err)
393      return err;
394
395   /* magic bytes present? */
396   if ((header[510] != 0x55) || (header[511] != 0xAA))
397      return IMGTOOLERR_CORRUPTIMAGE;
398
399   /* determine which type of FAT is on this disk */
400   if (!memcmp(&header[54], fat8_string, sizeof(fat8_string)))
401      fat_bits = 8;
402   else if (!memcmp(&header[54], fat12_string, sizeof(fat12_string)))
403      fat_bits = 12;
404   else if (!memcmp(&header[54], fat16_string, sizeof(fat16_string)))
405      fat_bits = 16;
406   else if (!memcmp(&header[54], fat32_string, sizeof(fat32_string)))
407      fat_bits = 32;
408   else
409   {
410      fat_bits = 8;
411      has_extended_bios_param_block = FALSE;
412   }
413   
414   info->fat_bits            = fat_bits;
415   sector_size               = pick_integer_le(header, 11, 2);
416   info->sectors_per_cluster   = pick_integer_le(header, 13, 1);
417   info->reserved_sectors      = pick_integer_le(header, 14, 2);
418   info->fat_count            = pick_integer_le(header, 16, 1);
419   info->root_entries         = pick_integer_le(header, 17, 2);
420   total_sectors_l            = pick_integer_le(header, 19, 2);
421   info->sectors_per_fat      = pick_integer_le(header, 22, 2);
422   total_sectors_h            = pick_integer_le(header, 32, 4);
423
424   if (info->sectors_per_cluster == 0)
425      return IMGTOOLERR_CORRUPTIMAGE;
426
427   info->total_sectors = total_sectors_l + (((UINT64) total_sectors_h) << 16);
428   available_sectors = info->total_sectors - info->reserved_sectors
429      - (info->sectors_per_fat * info->fat_count)
430      - (info->root_entries * FAT_DIRENT_SIZE + FAT_SECLEN - 1) / FAT_SECLEN;
431   info->total_clusters = (available_sectors + info->sectors_per_cluster - 1) / info->sectors_per_cluster;
432   info->cluster_size = FAT_SECLEN * info->sectors_per_cluster;
433
434   if (info->fat_count == 0)
435      return IMGTOOLERR_CORRUPTIMAGE;
436   if (sector_size != FAT_SECLEN)
437      return IMGTOOLERR_CORRUPTIMAGE;
438   if (info->sectors_per_fat == 0)
439      return IMGTOOLERR_CORRUPTIMAGE;
440   if (info->sectors_per_cluster == 0)
441      return IMGTOOLERR_CORRUPTIMAGE;
442   if (info->reserved_sectors == 0)
443      return IMGTOOLERR_CORRUPTIMAGE;
444   if (info->total_clusters * info->fat_bits > info->sectors_per_fat * FAT_SECLEN * 8)
445      return IMGTOOLERR_CORRUPTIMAGE;
446
447   return IMGTOOLERR_SUCCESS;
448}
449
450
451
452imgtoolerr_t fat_partition_create(imgtool_image *image, UINT64 first_block, UINT64 block_count)
453{
454   imgtoolerr_t err;
455   UINT32 heads, tracks, sectors_per_track;
456   UINT32 fat_bits, sectors_per_cluster, reserved_sectors, hidden_sectors;
457   UINT32 root_dir_count, root_dir_sectors;
458   UINT32 sectors_per_fat, fat_count, i;
459   UINT32 boot_sector_offset;
460   UINT64 total_clusters;
461   UINT8 media_descriptor;
462   const char *title;
463   const char *fat_bits_string;
464   UINT8 header[FAT_SECLEN];
465   UINT64 first_fat_entries;
466
467   /* check for limits */
468   if (block_count > U64(0xFFFFFFFFFFFF))
469      return IMGTOOLERR_PARAMTOOLARGE;
470
471   /* get the geometry */
472   err = imgtool_image_get_geometry(image, &tracks, &heads, &sectors_per_track);
473   if (err)
474      return err;
475
476   /* cap our sector count so that we only use FAT12/16 */
477   sectors_per_cluster = (block_count + 65524 - 1) / 65524;
478
479   /* compute the FAT file system type */
480   if ((block_count / sectors_per_cluster) <= 4084)
481   {
482      fat_bits = 12;
483      fat_bits_string = fat12_string;
484   }
485   else if ((block_count / sectors_per_cluster) <= 65524)
486   {
487      fat_bits = 16;
488      fat_bits_string = fat16_string;
489   }
490   else
491   {
492      fat_bits = 32;
493      fat_bits_string = fat32_string;
494   }
495
496   /* figure out media type */
497   i = 0;
498   while((known_media[i].heads > 0) && ((known_media[i].heads != heads)
499      || (known_media[i].tracks != tracks)
500      || (known_media[i].sectors != sectors_per_track)))
501   {
502      i++;
503   }
504   media_descriptor = known_media[i].media_descriptor;
505
506   /* other miscellaneous settings */
507   title = "";
508   fat_count = 2;
509   root_dir_count = 512;
510   hidden_sectors = 0;
511   reserved_sectors = 1;
512
513   /* calculated settings */
514   root_dir_sectors = (root_dir_count * FAT_DIRENT_SIZE + FAT_SECLEN - 1) / FAT_SECLEN;
515   total_clusters = (block_count - reserved_sectors - hidden_sectors - root_dir_sectors)
516      / sectors_per_cluster;
517   sectors_per_fat = (total_clusters * fat_bits + (FAT_SECLEN * 8) - 1)
518      / (FAT_SECLEN * 8);
519
520   /* prepare the header */
521   memset(header, 0, sizeof(header));
522   memcpy(&header[3], "IMGTOOL ", 8);
523   place_integer_le(header, 11, 2, FAT_SECLEN);
524   place_integer_le(header, 13, 1, sectors_per_cluster);
525   place_integer_le(header, 14, 1, reserved_sectors);
526   place_integer_le(header, 16, 1, fat_count);
527   place_integer_le(header, 17, 2, root_dir_count);
528   place_integer_le(header, 19, 2, (UINT16) (block_count >> 0));
529   place_integer_le(header, 21, 1, media_descriptor);
530   place_integer_le(header, 22, 2, sectors_per_fat);
531   place_integer_le(header, 24, 2, sectors_per_track);
532   place_integer_le(header, 26, 2, heads);
533   place_integer_le(header, 28, 4, hidden_sectors);
534   place_integer_le(header, 32, 4, (UINT32) (block_count >> 16));
535   place_integer_le(header, 36, 1, 0xFF);
536   place_integer_le(header, 38, 1, 0x28);
537   place_integer_le(header, 39, 4, imgtool_image_rand(image));
538   memcpy(&header[43], "           ", 11);
539   memcpy(&header[54], fat_bits_string, 8);
540
541   /* store boot code */
542   boot_sector_offset = sizeof(header) - sizeof(boot_sector_code);
543   if (boot_sector_offset < 62)
544      return IMGTOOLERR_UNEXPECTED;   /* sanity check */
545   if (boot_sector_offset > 510)
546      return IMGTOOLERR_UNEXPECTED;   /* sanity check */
547   memcpy(&header[boot_sector_offset], boot_sector_code, sizeof(boot_sector_code));
548
549   /* specify jump instruction */
550   if (boot_sector_offset <= 129)
551   {
552      header[0] = 0xEB;                            /* JMP rel8 */
553      header[1] = (UINT8) (boot_sector_offset - 2);       /* (offset) */
554      header[2] = 0x90;                            /* NOP */
555   }
556   else
557   {
558      header[0] = 0xE9;                            /* JMP rel16 */
559      header[1] = (UINT8) ((boot_sector_offset - 2) >> 0); /* (offset) */
560      header[2] = (UINT8) ((boot_sector_offset - 2) >> 8); /* (offset) */
561   }
562
563   err = imgtool_image_write_block(image, first_block, header);
564   if (err)
565      return err;
566
567   /* clear out file allocation table */
568   for (i = reserved_sectors; i < (reserved_sectors + sectors_per_fat * fat_count + root_dir_sectors); i++)
569   {
570      err = imgtool_image_clear_block(image, first_block + i, 0);
571      if (err)
572         return err;
573   }
574
575   /* set first two FAT entries */
576   first_fat_entries = ((UINT64) media_descriptor) | 0xFFFFFF00;
577   first_fat_entries &= (((UINT64) 1) << fat_bits) - 1;
578   first_fat_entries |= ((((UINT64) 1) << fat_bits) - 1) << fat_bits;
579   first_fat_entries = LITTLE_ENDIANIZE_INT64(first_fat_entries);
580
581   for (i = 0; i < fat_count; i++)
582   {
583      err = imgtool_image_write_block(image, first_block + 1 + (i * sectors_per_fat), &first_fat_entries);
584      if (err)
585         return err;
586   }
587
588   return IMGTOOLERR_SUCCESS;
589}
590
591
592
593static imgtoolerr_t fat_load_fat(imgtool_partition *partition, UINT8 **fat_table)
594{
595   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
596   const fat_partition_info *disk_info;
597   UINT8 *table;
598   UINT32 table_size;
599   UINT32 pos, len;
600   UINT32 sector_index;
601
602   disk_info = fat_get_partition_info(partition);
603
604   table_size = disk_info->sectors_per_fat * disk_info->fat_count * FAT_SECLEN;
605
606   /* allocate the table with extra bytes, in case we "overextend" our reads */
607   table = malloc(table_size + sizeof(UINT64));
608   if (!table)
609   {
610      err = IMGTOOLERR_OUTOFMEMORY;
611      goto done;
612   }
613   memset(table, 0, table_size + sizeof(UINT64));
614
615   pos = 0;
616   sector_index = disk_info->reserved_sectors;
617
618   while(pos < table_size)
619   {
620      len = MIN(table_size - pos, FAT_SECLEN);
621
622      err = fat_read_sector(partition, sector_index++, 0, &table[pos], len);
623      if (err)
624         goto done;
625
626      pos += FAT_SECLEN;
627   }
628
629done:
630   if (err && table)
631   {
632      free(table);
633      table = NULL;
634   }
635   *fat_table = table;
636   return err;
637}
638
639
640
641static imgtoolerr_t fat_save_fat(imgtool_partition *partition, const UINT8 *fat_table)
642{
643   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
644   const fat_partition_info *disk_info;
645   UINT32 table_size;
646   UINT32 pos, len;
647   UINT32 sector_index;
648
649   disk_info = fat_get_partition_info(partition);
650
651   table_size = disk_info->sectors_per_fat * disk_info->fat_count * FAT_SECLEN;
652
653   pos = 0;
654   sector_index = disk_info->reserved_sectors;
655
656   while(pos < table_size)
657   {
658      len = MIN(table_size - pos, FAT_SECLEN);
659
660      err = fat_write_sector(partition, sector_index++, 0, &fat_table[pos], len);
661      if (err)
662         goto done;
663
664      pos += FAT_SECLEN;
665   }
666
667done:
668   return err;
669}
670
671
672
673static UINT32 fat_get_fat_entry(imgtool_partition *partition, const UINT8 *fat_table, UINT32 fat_entry)
674{
675   const fat_partition_info *disk_info;
676   UINT64 entry;
677   UINT32 bit_index, i;
678   UINT32 last_entry = 0;
679   UINT32 bit_mask;
680
681   disk_info = fat_get_partition_info(partition);
682   bit_index = fat_entry * disk_info->fat_bits;
683   bit_mask = 0xFFFFFFFF >> (32 - disk_info->fat_bits);
684
685   if (fat_entry >= disk_info->total_clusters)
686   {
687      assert(0);
688      return 1;
689   }
690
691   /* make sure that the cluster is free in all fats */
692   for (i = 0; i < disk_info->fat_count; i++)
693   {
694      memcpy(&entry, fat_table + (i * FAT_SECLEN
695         * disk_info->sectors_per_fat) + (bit_index / 8), sizeof(entry));
696
697      /* we've extracted the bytes; we now need to normalize it */
698      entry = LITTLE_ENDIANIZE_INT64(entry);
699      entry >>= bit_index % 8;
700      entry &= bit_mask;
701
702      if (i == 0)
703         last_entry = (UINT32) entry;
704      else if (last_entry != (UINT32) entry)
705         return 1;   /* if the FATs disagree; mark this as reserved */
706   }
707   
708   /* normalize special clusters */
709   if (last_entry >= (0xFFFFFFF0 & bit_mask))
710   {
711      last_entry |= 0xFFFFFFF0;
712      if (last_entry >= 0xFFFFFFF8)
713         last_entry = 0xFFFFFFFF;
714   }
715   return last_entry;
716}
717
718
719
720static void fat_set_fat_entry(imgtool_partition *partition, UINT8 *fat_table, UINT32 fat_entry, UINT32 value)
721{
722   const fat_partition_info *disk_info;
723   UINT64 entry;
724   UINT32 bit_index, i;
725
726   disk_info = fat_get_partition_info(partition);
727   bit_index = fat_entry * disk_info->fat_bits;
728   value &= 0xFFFFFFFF >> (32 - disk_info->fat_bits);
729
730   for (i = 0; i < disk_info->fat_count; i++)
731   {
732      memcpy(&entry, fat_table + (i * FAT_SECLEN
733         * disk_info->sectors_per_fat) + (bit_index / 8), sizeof(entry));
734
735      entry = LITTLE_ENDIANIZE_INT64(entry);
736      entry &= (~((UINT64) 0xFFFFFFFF >> (32 - disk_info->fat_bits)) << (bit_index % 8)) | ((1 << (bit_index % 8)) - 1);
737      entry |= ((UINT64) value) << (bit_index % 8);
738      entry = LITTLE_ENDIANIZE_INT64(entry);
739
740      memcpy(fat_table + (i * FAT_SECLEN
741         * disk_info->sectors_per_fat) + (bit_index / 8), &entry, sizeof(entry));
742   }
743}
744
745
746
747static void fat_debug_integrity_check(imgtool_partition *partition, const UINT8 *fat_table, const fat_file *file)
748{
749#ifdef MAME_DEBUG
750   /* debug function to test the integrity of a file */
751   UINT32 cluster;
752   const fat_partition_info *disk_info;
753
754   disk_info = fat_get_partition_info(partition);
755   cluster = file->first_cluster ? file->first_cluster : 0xFFFFFFFF;
756
757   if (!file->root)
758   {
759      while(cluster != 0xFFFFFFFF)
760      {
761         assert((cluster >= 2) && (cluster < disk_info->total_clusters));
762         cluster = fat_get_fat_entry(partition, fat_table, cluster);
763      }
764   }
765#endif
766}
767
768
769
770static imgtoolerr_t fat_seek_file(imgtool_partition *partition, fat_file *file, UINT32 pos)
771{
772   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
773   const fat_partition_info *disk_info;
774   UINT32 new_cluster;
775   UINT8 *fat_table = NULL;
776
777   disk_info = fat_get_partition_info(partition);
778
779   /* can't seek past end of file */
780   if (!file->directory && (pos > file->filesize))
781      pos = file->filesize;
782
783   if (file->first_cluster == 0)
784   {
785      /* special case; the root directory */
786      file->index = pos;
787   }
788   else
789   {
790      /* first, we need to check to see if we have to go back to the beginning */
791      if (pos < file->index)
792      {
793         file->cluster = file->first_cluster;
794         file->cluster_index = 0;
795         file->eof = 0;
796      }
797
798      /* skip ahead clusters */
799      while((file->cluster_index + disk_info->cluster_size) <= pos)
800      {
801         if (!fat_table)
802         {
803            err = fat_load_fat(partition, &fat_table);
804            if (err)
805               goto done;
806         }
807
808         new_cluster = fat_get_fat_entry(partition, fat_table, file->cluster);
809
810         file->cluster = new_cluster;
811         file->cluster_index += disk_info->cluster_size;
812
813         /* are we at the end of the file? */
814         if (new_cluster == 0xFFFFFFFF)
815         {
816            pos = file->cluster_index;
817            file->eof = 1;
818         }
819      }
820      file->index = pos;
821   }
822
823done:
824   if (fat_table)
825      free(fat_table);
826   return err;
827}
828
829
830
831static UINT32 fat_get_filepos_sector_index(imgtool_partition *partition, fat_file *file)
832{
833   UINT32 sector_index;
834   const fat_partition_info *disk_info;
835
836   disk_info = fat_get_partition_info(partition);
837
838   sector_index = disk_info->reserved_sectors + (disk_info->sectors_per_fat * disk_info->fat_count);
839   if (file->root)
840   {
841      /* special case for the root file */
842      sector_index += file->index / FAT_SECLEN;
843   }
844   else
845   {
846      /* cluster out of range? */
847      if ((file->cluster < 2) || (file->cluster >= disk_info->total_clusters))
848         return 0;
849
850      sector_index += (disk_info->root_entries * FAT_DIRENT_SIZE + FAT_SECLEN - 1) / FAT_SECLEN;
851      sector_index += (file->cluster - 2) * disk_info->sectors_per_cluster;
852      sector_index += (file->index / FAT_SECLEN) % disk_info->sectors_per_cluster;
853   }
854   return sector_index;
855}
856
857
858
859static imgtoolerr_t fat_corrupt_file_error(const fat_file *file)
860{
861   imgtoolerr_t err;
862   if (file->root)
863      err = IMGTOOLERR_CORRUPTIMAGE;
864   else if (file->directory)
865      err = IMGTOOLERR_CORRUPTDIR;
866   else
867      err = IMGTOOLERR_CORRUPTFILE;
868   return err;
869}
870
871
872
873static imgtoolerr_t fat_readwrite_file(imgtool_partition *partition, fat_file *file,
874   void *buffer, size_t buffer_len, size_t *bytes_read, int read_or_write)
875{
876   imgtoolerr_t err;
877   const fat_partition_info *disk_info;
878   UINT32 sector_index;
879   int offset;
880   size_t len;
881
882   disk_info = fat_get_partition_info(partition);
883   if (bytes_read)
884      *bytes_read = 0;
885   if (!file->directory)
886      buffer_len = MIN(buffer_len, file->filesize - file->index);
887
888   while(!file->eof && (buffer_len > 0))
889   {
890      sector_index = fat_get_filepos_sector_index(partition, file);
891      if (sector_index == 0)
892         return fat_corrupt_file_error(file);
893
894      offset = file->index % FAT_SECLEN;
895      len = MIN(buffer_len, FAT_SECLEN - offset);
896
897      /* read or write the data from the disk */
898      if (read_or_write)
899         err = fat_write_sector(partition, sector_index, offset, buffer, len);
900      else
901         err = fat_read_sector(partition, sector_index, offset, buffer, len);
902      if (err)
903         return err;
904
905      /* and move the file pointer ahead */
906      err = fat_seek_file(partition, file, file->index + len);
907      if (err)
908         return err;
909
910      buffer = ((UINT8 *) buffer) + len;
911      buffer_len -= len;
912      if (bytes_read)
913         *bytes_read += len;
914   }
915   return IMGTOOLERR_SUCCESS;
916}
917
918
919
920static imgtoolerr_t fat_read_file(imgtool_partition *partition, fat_file *file,
921   void *buffer, size_t buffer_len, size_t *bytes_read)
922{
923   return fat_readwrite_file(partition, file, buffer, buffer_len, bytes_read, 0);
924}
925
926
927
928static imgtoolerr_t fat_write_file(imgtool_partition *partition, fat_file *file,
929   const void *buffer, size_t buffer_len, size_t *bytes_read)
930{
931   return fat_readwrite_file(partition, file, (void *) buffer, buffer_len, bytes_read, 1);
932}
933
934
935
936static UINT32 fat_allocate_cluster(imgtool_partition *partition, UINT8 *fat_table)
937{
938   const fat_partition_info *disk_info;
939   UINT32 i, val;
940
941   disk_info = fat_get_partition_info(partition);
942
943   for (i = 2; i < disk_info->total_clusters; i++)
944   {
945      val = fat_get_fat_entry(partition, fat_table, i);
946      if (val == 0)
947      {
948         fat_set_fat_entry(partition, fat_table, i, 1);
949         return i;
950      }
951   }
952   return 0;
953}
954
955
956
957/* sets the size of a file; ~0 means 'delete' */
958static imgtoolerr_t fat_set_file_size(imgtool_partition *partition, fat_file *file,
959   UINT32 new_size)
960{
961   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
962   const fat_partition_info *disk_info;
963   UINT32 new_cluster_count;
964   UINT32 old_cluster_count;
965   UINT32 cluster, write_cluster, last_cluster, new_pos, i;
966   UINT8 *fat_table = NULL;
967   UINT8 dirent[32];
968   size_t clear_size;
969   void *clear_buffer = NULL;
970   int delete_file = FALSE;
971   int rest_free = FALSE;
972
973   disk_info = fat_get_partition_info(partition);
974
975   LOG(("fat_set_file_size(): file->first_cluster=%d new_size=0x%08x\n", file->first_cluster, new_size));
976
977   /* special case */
978   if (new_size == ~0)
979   {
980      delete_file = TRUE;
981      new_size = 0;
982   }
983   
984   /* if this is the trivial case (not changing the size), succeed */
985   if (!delete_file && (file->filesize == new_size))
986   {
987      err = IMGTOOLERR_SUCCESS;
988      goto done;
989   }
990
991   /* what is the new position? */
992   new_pos = MIN(file->index, new_size);
993
994   if (file->root)
995   {
996      /* this is the root directory; this is a special case */
997      if (new_size > (disk_info->root_entries * FAT_DIRENT_SIZE))
998      {
999         err = IMGTOOLERR_NOSPACE;
1000         goto done;
1001      }
1002   }
1003   else
1004   {
1005      old_cluster_count = (file->filesize + disk_info->cluster_size - 1) / disk_info->cluster_size;
1006      new_cluster_count = (new_size + disk_info->cluster_size - 1) / disk_info->cluster_size;
1007      cluster = 0;
1008
1009      /* load the dirent */
1010      err = fat_read_sector(partition, file->dirent_sector_index, file->dirent_sector_offset, dirent, sizeof(dirent));
1011      if (err)
1012         goto done;
1013
1014      /* need to load the FAT whether we are growing or shrinking the file */
1015      if (old_cluster_count != new_cluster_count)
1016      {
1017         err = fat_load_fat(partition, &fat_table);
1018         if (err)
1019            goto done;
1020
1021         cluster = 0;
1022         i = 0;
1023         do
1024         {
1025            last_cluster = cluster;
1026            write_cluster = 0;
1027
1028            /* identify the next cluster */
1029            if (cluster != 0)
1030               cluster = fat_get_fat_entry(partition, fat_table, cluster);
1031            else
1032               cluster = file->first_cluster ? file->first_cluster : 0xFFFFFFFF;
1033
1034            /* do we need to grow the file by a cluster? */
1035            if (i < new_cluster_count && ((cluster < 2) || (cluster >= disk_info->total_clusters)))
1036            {
1037               /* grow this file by a cluster */
1038               cluster = fat_allocate_cluster(partition, fat_table);
1039               if (cluster == 0)
1040               {
1041                  err = IMGTOOLERR_NOSPACE;
1042                  goto done;
1043               }
1044               
1045               write_cluster = cluster;
1046            }
1047            else if (i >= new_cluster_count)
1048            {
1049               /* we are shrinking the file; we need to unlink this node */
1050               if ((cluster < 2) || (cluster >= disk_info->total_clusters))
1051                  cluster = 0xFFFFFFFF; /* ack file is corrupt! recover */
1052               write_cluster = 0xFFFFFFFF;
1053            }
1054
1055            /* write out the entry, if appropriate */
1056            if (write_cluster != 0)
1057            {
1058               /* are we tieing up loose ends? */
1059               if (rest_free && (write_cluster == 0xFFFFFFFF))
1060                  write_cluster = 0;
1061
1062               if (last_cluster == 0)
1063                  file->first_cluster = (write_cluster != 0xFFFFFFFF) ? write_cluster : 0;
1064               else
1065                  fat_set_fat_entry(partition, fat_table, last_cluster, write_cluster);
1066
1067               /* did we write the last cluster?  if so, the rest (if any) are free */
1068               if (write_cluster == 0xFFFFFFFF)
1069                  rest_free = TRUE;
1070            }
1071         }
1072         while((++i < new_cluster_count) || (cluster != 0xFFFFFFFF));
1073      }
1074
1075      /* record the new file size */
1076      place_integer_le(dirent, 26, 2, file->first_cluster);
1077      place_integer_le(dirent, 28, 4, new_size);
1078
1079      /* delete the file, if appropriate */
1080      if (delete_file)
1081         dirent[0] = 0xE5;
1082
1083      /* save the dirent */
1084      err = fat_write_sector(partition, file->dirent_sector_index, file->dirent_sector_offset, dirent, sizeof(dirent));
1085      if (err)
1086         goto done;
1087
1088      /* if we've modified the FAT, save it out */
1089      if (fat_table)
1090      {
1091         err = fat_save_fat(partition, fat_table);
1092         if (err)
1093            goto done;
1094      }
1095
1096      /* update the file structure */
1097      if (!file->directory)
1098         file->filesize = new_size;
1099      file->cluster = file->first_cluster;
1100      file->index = 0;
1101      file->cluster_index = 0;
1102      file->eof = (new_cluster_count == 0);
1103   }
1104
1105   /* special case; clear out stale bytes on non-root directories */
1106   if (file->directory && !delete_file)
1107   {
1108      if (file->root)
1109         clear_size = MIN(file->filesize - new_size, FAT_DIRENT_SIZE);
1110      else
1111         clear_size = (disk_info->cluster_size - (new_size % disk_info->cluster_size)) % disk_info->cluster_size;
1112
1113      if (clear_size > 0)
1114      {
1115         err = fat_seek_file(partition, file, new_size);
1116         if (err)
1117            goto done;
1118
1119         clear_buffer = malloc(clear_size);
1120         if (!clear_buffer)
1121         {
1122            err = IMGTOOLERR_OUTOFMEMORY;
1123            goto done;
1124         }
1125         memset(clear_buffer, '\0', clear_size);
1126
1127         err = fat_write_file(partition, file, clear_buffer, clear_size, NULL);
1128         if (err)
1129            goto done;
1130      }
1131   }
1132
1133   /* seek back to original pos */
1134   err = fat_seek_file(partition, file, new_pos);
1135   if (err)
1136      goto done;
1137
1138   if (fat_table)
1139      fat_debug_integrity_check(partition, fat_table, file);
1140
1141done:
1142   if (fat_table)
1143      free(fat_table);
1144   if (clear_buffer)
1145      free(clear_buffer);
1146   return err;
1147}
1148
1149
1150
1151static void prepend_lfn_bytes(utf16_char *lfn_buf, size_t lfn_buflen, size_t *lfn_len,
1152   const UINT8 *entry, int offset, int chars)
1153{
1154   UINT16 w;
1155   int i;
1156   size_t move_len;
1157
1158   move_len = MIN(*lfn_len + 1, lfn_buflen - chars - 1);
1159   memmove(&lfn_buf[chars], &lfn_buf[0], move_len * sizeof(*lfn_buf));
1160
1161   for (i = 0; i < chars; i++)
1162   {
1163      /* read the character */
1164      memcpy(&w, &entry[offset + i * 2], 2);
1165      w = LITTLE_ENDIANIZE_INT16(w);
1166
1167      /* append to buffer */
1168      lfn_buf[i] = (w != 0xFFFF) ? w : 0;
1169   }
1170   *lfn_len += chars;
1171}
1172
1173
1174
1175static UINT8 fat_calc_filename_checksum(const UINT8 *short_filename)
1176{
1177   UINT8 checksum;
1178   int i, j;
1179
1180   checksum = 0;
1181   for (i = 0; i < 11; i++)
1182   {
1183      j = checksum & 1;
1184      checksum >>= 1;
1185      if (j)
1186         checksum |= 0x80;
1187      checksum += short_filename[i];
1188   }
1189   return checksum;
1190}
1191
1192
1193
1194static void fat_calc_dirent_lfnchecksum(UINT8 *entry, size_t entry_len)
1195{
1196   UINT8 checksum;
1197   int i;
1198
1199   checksum = fat_calc_filename_checksum(entry + entry_len - FAT_DIRENT_SIZE);
1200
1201   for (i = 0; i < (entry_len / FAT_DIRENT_SIZE - 1); i++)
1202      entry[i * FAT_DIRENT_SIZE + 13] = checksum;
1203}
1204
1205
1206
1207static char fat_cannonicalize_sfn_char(char ch)
1208{
1209   /* return the display version of this short file name character */
1210   return tolower(ch);
1211}
1212
1213
1214
1215static void fat_cannonicalize_sfn(char *sfn, const UINT8 *sfn_bytes)
1216{
1217   /* return the display version of this short file name */
1218   int i;
1219
1220   memset(sfn, '\0', 13);
1221   memcpy(sfn, sfn_bytes, 8);
1222   rtrim(sfn);
1223   if (sfn[0] == 0x05)
1224      sfn[0] = (char) 0xE5;
1225   if ((sfn_bytes[8] != ' ') || (sfn_bytes[9] != ' ') || (sfn_bytes[10] != ' '))
1226   {
1227      strcat(sfn, ".");
1228      memcpy(sfn + strlen(sfn), &sfn_bytes[8], 3);
1229      rtrim(sfn);
1230   }
1231   for (i = 0; sfn[i]; i++)
1232      sfn[i] = fat_cannonicalize_sfn_char(sfn[i]);
1233}
1234
1235
1236
1237static time_t fat_crack_time(UINT32 fat_time)
1238{
1239   struct tm t;
1240   time_t now;
1241
1242   time(&now);
1243   t = *localtime(&now);
1244
1245   t.tm_sec   = ((fat_time >>  0) & 0x001F) * 2;
1246   t.tm_min   = ((fat_time >>  5) & 0x003F);
1247   t.tm_hour   = ((fat_time >> 11) & 0x001F);
1248   t.tm_mday   = ((fat_time >> 16) & 0x001F);
1249   t.tm_mon   = ((fat_time >> 21) & 0x000F);
1250   t.tm_year   = ((fat_time >> 25) & 0x007F) + 1980 - 1900;
1251
1252   return mktime(&t);
1253}
1254
1255
1256
1257static UINT32 fat_setup_time(time_t ansi_time)
1258{
1259   struct tm t;
1260   UINT32 result = 0;
1261
1262   t = *localtime(&ansi_time);
1263
1264   result |= (((UINT32) (t.tm_sec / 2))         & 0x001F) <<  0;
1265   result |= (((UINT32) t.tm_min)               & 0x003F) <<  5;
1266   result |= (((UINT32) t.tm_hour)               & 0x001F) << 11;
1267   result |= (((UINT32) t.tm_mday)               & 0x001F) << 16;
1268   result |= (((UINT32) t.tm_mon)               & 0x000F) << 21;
1269   result |= (((UINT32) (t.tm_year + 1900 - 1980))   & 0x007F) << 25;
1270
1271   return result;
1272}
1273
1274
1275
1276static imgtoolerr_t fat_read_dirent(imgtool_partition *partition, fat_file *file,
1277   fat_dirent *ent, fat_freeentry_info *freeent)
1278{
1279   imgtoolerr_t err;
1280   const fat_partition_info *disk_info;
1281   UINT8 entry[FAT_DIRENT_SIZE];
1282   size_t bytes_read;
1283   int i, j;
1284   unicode_char ch;
1285   utf16_char lfn_buf[512];
1286   size_t lfn_len = 0;
1287   int lfn_lastentry = 0;
1288   UINT8 lfn_checksum = 0;
1289   UINT32 entry_index, entry_sector_index, entry_sector_offset;
1290
1291   assert(file->directory);
1292   lfn_buf[0] = '\0';
1293   memset(ent, 0, sizeof(*ent));
1294   disk_info = fat_get_partition_info(partition);
1295
1296   /* The first eight bytes of a FAT directory entry is a blank padded name
1297    *
1298    * The first byte can be special:
1299    *   0x00 - entry is available and no further entry is used
1300    *   0x05 - first character is actually 0xe5
1301    *   0x2E - dot entry; either '.' or '..'
1302    *   0xE5 - entry has been erased and is available
1303    *
1304    * Byte 11 is the attributes; and 0x0F denotes a LFN entry
1305    */
1306   do
1307   {
1308      entry_index = file->index;
1309      entry_sector_index = fat_get_filepos_sector_index(partition, file);
1310      entry_sector_offset = file->index % FAT_SECLEN;
1311
1312      err = fat_read_file(partition, file, entry, sizeof(entry), &bytes_read);
1313      if (err)
1314         return err;
1315      if (bytes_read < sizeof(entry))
1316         memset(entry, 0, sizeof(entry));
1317
1318      if (entry[11] == 0x0F)
1319      {
1320         /* this is an LFN entry */
1321         if ((lfn_lastentry == 0)
1322            || ((entry[0] & 0x3F) != (lfn_lastentry - 1))
1323            || (lfn_checksum != entry[13]))
1324         {
1325            lfn_buf[0] = 0;
1326            lfn_len = 0;
1327            lfn_checksum = entry[13];
1328         }
1329         lfn_lastentry = entry[0] & 0x3F;
1330         prepend_lfn_bytes(lfn_buf, sizeof(lfn_buf) / sizeof(lfn_buf[0]),
1331            &lfn_len, entry, 28, 2);
1332         prepend_lfn_bytes(lfn_buf, sizeof(lfn_buf) / sizeof(lfn_buf[0]),
1333            &lfn_len, entry, 14, 6);
1334         prepend_lfn_bytes(lfn_buf, sizeof(lfn_buf) / sizeof(lfn_buf[0]),
1335            &lfn_len, entry,  1, 5);
1336      }
1337      else if (freeent && (freeent->position == ~0))
1338      {
1339         /* do a quick check to find out if we found space */
1340         if ((entry[0] == '\0') || (entry[0] == 0xE5))
1341         {
1342            if (freeent->candidate_position > entry_index)
1343               freeent->candidate_position = entry_index;
1344
1345            if ((entry[0] == '\0') || (freeent->candidate_position + freeent->required_size < file->index))
1346               freeent->position = freeent->candidate_position;
1347         }
1348         else
1349         {
1350            freeent->candidate_position = ~0;
1351         }
1352      }
1353   }
1354   while((entry[0] == 0x2E) || (entry[0] == 0xE5) || (entry[11] == 0x0F));
1355
1356   /* no more directory entries? */
1357   if (entry[0] == '\0')
1358   {
1359      ent->eof = 1;
1360      return IMGTOOLERR_SUCCESS;
1361   }
1362
1363   /* pick apart short filename */
1364   fat_cannonicalize_sfn(ent->short_filename, entry);
1365
1366   /* and the long filename */
1367   if (lfn_lastentry == 1)
1368   {
1369      /* only use the LFN if the checksum passes */
1370      if (lfn_checksum == fat_calc_filename_checksum(entry))
1371      {
1372         i = 0;
1373         j = 0;
1374         do
1375         {
1376            i += uchar_from_utf16(&ch, &lfn_buf[i], sizeof(lfn_buf) / sizeof(lfn_buf[0]) - i);
1377            j += utf8_from_uchar(&ent->long_filename[j], sizeof(ent->long_filename) / sizeof(ent->long_filename[0]) - j, ch);
1378         }
1379         while(ch != 0);
1380      }
1381   }
1382
1383   /* other attributes */
1384   ent->filesize            = pick_integer_le(entry, 28, 4);
1385   ent->directory            = (entry[11] & 0x10) ? 1 : 0;
1386   ent->first_cluster         = pick_integer_le(entry, 26, 2);
1387   ent->dirent_sector_index   = entry_sector_index;
1388   ent->dirent_sector_offset   = entry_sector_offset;
1389   ent->creation_time         = fat_crack_time(pick_integer_le(entry, 14, 4));
1390   ent->lastmodified_time      = fat_crack_time(pick_integer_le(entry, 22, 4));
1391   return IMGTOOLERR_SUCCESS;
1392}
1393
1394
1395
1396typedef enum
1397{
1398   SFN_SUFFICIENT,   /* name fully representable in short file name */
1399   SFN_DERIVATIVE,   /* name not fully representable in short file name, but no need to tildize */
1400   SFN_MANGLED      /* name not representable in short file name; must tildize */
1401} sfn_disposition_t;
1402
1403static imgtoolerr_t fat_construct_dirent(const char *filename, creation_policy_t create,
1404   UINT8 **entry, size_t *entry_len)
1405{
1406   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
1407   UINT8 *created_entry = NULL;
1408   UINT8 *new_created_entry;
1409   UINT32 now;
1410   size_t created_entry_len = FAT_DIRENT_SIZE;
1411   size_t created_entry_pos = 0;
1412   unicode_char ch;
1413   char last_short_char = ' ';
1414   char short_char = '\0';
1415   char cannonical_short_char;
1416   utf16_char buf[UTF16_CHAR_MAX];
1417   int i, len;
1418   int sfn_pos = 0;
1419   sfn_disposition_t sfn_disposition = SFN_SUFFICIENT;
1420   int sfn_in_extension = 0;
1421
1422   /* sanity check */
1423   if (*filename == '\0')
1424   {
1425      err = IMGTOOLERR_BADFILENAME;
1426      goto done;
1427   }
1428
1429   /* construct intial entry */
1430   created_entry = (UINT8 *) malloc(FAT_DIRENT_SIZE);
1431   if (!created_entry)
1432   {
1433      err = IMGTOOLERR_OUTOFMEMORY;
1434      goto done;
1435   }
1436
1437   /* set up the basics for the new dirent */
1438   memset(created_entry +  0, ' ', 11);
1439   memset(created_entry + 12, '\0', FAT_DIRENT_SIZE - 12);
1440   created_entry[11] = (create == CREATE_DIR) ? 0x10 : 0x00;
1441   
1442   /* set up file dates in the new dirent */
1443   now = fat_setup_time(time(NULL));
1444   place_integer_le(created_entry, 14, 4, now);
1445   place_integer_le(created_entry, 18, 2, now);
1446   place_integer_le(created_entry, 22, 4, now);
1447
1448   while(*filename)
1449   {
1450      filename += uchar_from_utf8(&ch, filename, UTF8_CHAR_MAX);
1451
1452      /* append to short filename, if possible */
1453      if ((ch < 32) || (ch > 128))
1454         short_char = '\0';
1455      else if (isalnum((char) ch))
1456         short_char = toupper((char) ch);
1457      else if (strchr(".!#$%^()-@^_`{}~", (char) ch))
1458         short_char = (char) ch;
1459      else
1460         short_char = '\0';   /* illegal SFN char */
1461      cannonical_short_char = fat_cannonicalize_sfn_char((char) ch);
1462      if (!short_char || (short_char != cannonical_short_char))
1463      {
1464         if (toupper(short_char) == toupper(cannonical_short_char))
1465            sfn_disposition = MAX(sfn_disposition, SFN_DERIVATIVE);
1466         else
1467            sfn_disposition = SFN_MANGLED;
1468      }
1469
1470      /* append the short filename char */
1471      if (short_char == '.')
1472      {
1473         /* multiple extensions or trailing spaces? */
1474         if (sfn_in_extension)
1475            sfn_disposition = SFN_MANGLED;
1476         else if (last_short_char == ' ')
1477            sfn_disposition = MAX(sfn_disposition, SFN_DERIVATIVE);
1478
1479         sfn_in_extension = 1;
1480         sfn_pos = 8;
1481         created_entry[created_entry_len - FAT_DIRENT_SIZE + 8] = ' ';
1482         created_entry[created_entry_len - FAT_DIRENT_SIZE + 9] = ' ';
1483         created_entry[created_entry_len - FAT_DIRENT_SIZE + 10] = ' ';
1484      }
1485      else if (sfn_pos == (sfn_in_extension ? 11 : 8))
1486      {
1487         /* ran out of characters for short filename */
1488         sfn_disposition = SFN_MANGLED;
1489      }
1490      else if (short_char != '\0')
1491      {
1492         created_entry[created_entry_len - FAT_DIRENT_SIZE + sfn_pos++] = short_char;
1493      }
1494      last_short_char = short_char;
1495
1496
1497      /* convert to UTF-16 and add a long filename entry */
1498      len = utf16le_from_uchar(buf, UTF16_CHAR_MAX, ch);
1499      for (i = 0; i < len; i++)
1500      {
1501         switch(created_entry_pos)
1502         {
1503            case 0:
1504            case 32:
1505               /* need to grow */
1506               new_created_entry = (UINT8 *) realloc(created_entry, created_entry_len + FAT_DIRENT_SIZE);
1507               if (!new_created_entry)
1508               {
1509                  err = IMGTOOLERR_OUTOFMEMORY;
1510                  goto done;
1511               }
1512               created_entry = new_created_entry;
1513
1514               /* move existing entries forward */
1515               memmove(created_entry + 32, created_entry, created_entry_len);
1516               created_entry_len += 32;
1517
1518               /* set up this LFN */
1519               memset(created_entry, '\0', 32);
1520               memset(&created_entry[1], '\xFF', 10);
1521               memset(&created_entry[14], '\xFF', 12);
1522               memset(&created_entry[28], '\xFF', 4);
1523               created_entry[11] = 0x0F;
1524
1525               /* specify entry index */
1526               created_entry[0] = (created_entry_len / 32) - 1;
1527               if (created_entry[0] >= 0x40)
1528               {
1529                  err = IMGTOOLERR_BADFILENAME;
1530                  goto done;
1531               }
1532               created_entry_pos = 1;
1533               break;
1534
1535            case 11:
1536               created_entry_pos = 14;
1537               break;
1538
1539            case 26:
1540               created_entry_pos = 28;
1541               break;
1542         }
1543
1544         memcpy(&created_entry[created_entry_pos], &buf[i], 2);
1545         created_entry_pos += 2;
1546      }
1547   }
1548
1549   /* trailing spaces? */
1550   if (short_char == ' ')
1551      sfn_disposition = MAX(sfn_disposition, SFN_DERIVATIVE);
1552
1553   if (sfn_disposition == SFN_SUFFICIENT)
1554   {
1555      /* the short filename suffices; remove the LFN stuff */
1556      memcpy(created_entry, created_entry + created_entry_len - FAT_DIRENT_SIZE, FAT_DIRENT_SIZE);
1557      created_entry_len = FAT_DIRENT_SIZE;
1558
1559      new_created_entry = (UINT8 *) realloc(created_entry, created_entry_len);
1560      if (!new_created_entry)
1561      {
1562         err = IMGTOOLERR_OUTOFMEMORY;
1563         goto done;
1564      }
1565      created_entry = new_created_entry;
1566   }
1567   else
1568   {
1569      /* need to do finishing touches on the LFN */
1570      created_entry[0] |= 0x40;
1571
1572      /* if necessary, mangle the name */
1573      if (sfn_disposition == SFN_MANGLED)
1574      {
1575         i = 6;
1576         while((i > 0) && isspace(created_entry[created_entry_len - FAT_DIRENT_SIZE + i - 1]))
1577            i--;
1578         created_entry[created_entry_len - FAT_DIRENT_SIZE + i + 0] = '~';
1579         created_entry[created_entry_len - FAT_DIRENT_SIZE + i + 1] = '1';
1580      }
1581      fat_calc_dirent_lfnchecksum(created_entry, created_entry_len);
1582   }
1583
1584done:
1585   if (err && created_entry)
1586   {
1587      free(created_entry);
1588      created_entry = NULL;
1589   }
1590   *entry = created_entry;
1591   *entry_len = created_entry_len;
1592   return err;
1593}
1594
1595
1596
1597static void fat_bump_dirent(imgtool_partition *partition, UINT8 *entry, size_t entry_len)
1598{
1599   UINT8 *sfn_entry;
1600   int pos, digit_count, i;
1601   UINT32 digit_place, val = 0;
1602   
1603   sfn_entry = &entry[entry_len - FAT_DIRENT_SIZE];
1604
1605   digit_place = 1;
1606   for (pos = 7; (pos >= 0) && isdigit((char) sfn_entry[pos]); pos--)
1607   {
1608      val += (sfn_entry[pos] - '0') * digit_place;
1609      digit_place *= 10;
1610   }
1611   val++;
1612   pos++;
1613
1614   /* count the digits */
1615   digit_place = 1;
1616   digit_count = 1;
1617   while(val >= digit_place * 10)
1618   {
1619      digit_count++;
1620      digit_place *= 10;
1621   }
1622
1623   /* give us some more space, if necessary */
1624   while ((pos > 0) && ((pos + digit_count) > 8))
1625      pos--;
1626
1627   /* have we actually ran out of digits */
1628   if ((pos + digit_count) > 8)
1629   {
1630      /* extreme degenerate case; simply randomize the filename */
1631      for (i = 0; i < 6; i++)
1632         sfn_entry[i] = 'A' + (imgtool_partition_rand(partition) % 26);
1633      sfn_entry[6] = '~';
1634      sfn_entry[7] = '0';
1635   }
1636   else
1637   {
1638      /* write the tilde, if possible */
1639      if (pos > 0)
1640         sfn_entry[pos - 1] = '~';
1641
1642      /* write out the number */
1643      while(digit_place > 0)
1644      {
1645         sfn_entry[pos++] = (val / digit_place) + '0';
1646         val %= digit_place;
1647         digit_place /= 10;
1648      }
1649   }
1650
1651   /* since we changed the short file name, we need to recalc the checksums
1652    * in the LFN entries */
1653   fat_calc_dirent_lfnchecksum(entry, entry_len);
1654}
1655
1656
1657
1658static imgtoolerr_t fat_lookup_path(imgtool_partition *partition, const char *path,
1659   creation_policy_t create, fat_file *file)
1660{
1661   imgtoolerr_t err;
1662   const fat_partition_info *disk_info;
1663   fat_dirent ent;
1664   fat_freeentry_info freeent = { 0, };
1665   const char *next_path_part;
1666   UINT8 *created_entry = NULL;
1667   size_t created_entry_len = 0;
1668   UINT32 entry_sector_index, entry_sector_offset;
1669   UINT32 parent_first_cluster;
1670   int bumped_sfn;
1671   char sfn[13];
1672
1673   disk_info = fat_get_partition_info(partition);
1674
1675   memset(file, 0, sizeof(*file));
1676   file->root = 1;
1677   file->directory = 1;
1678   file->filesize = disk_info->root_entries * FAT_DIRENT_SIZE;
1679
1680   while(*path)
1681   {
1682      if (!file->directory)
1683      {
1684         err = IMGTOOLERR_PATHNOTFOUND;
1685         goto done;
1686      }
1687
1688      next_path_part = path + strlen(path) + 1;
1689      if (create && (*next_path_part == '\0'))
1690      {
1691         /* this is the last entry, and we are creating a file */
1692         err = fat_construct_dirent(path, create, &created_entry, &created_entry_len);
1693         if (err)
1694            goto done;
1695
1696         freeent.required_size = created_entry_len;
1697         freeent.candidate_position = ~0;
1698         freeent.position = ~0;
1699      }
1700
1701      do
1702      {
1703         err = fat_read_dirent(partition, file, &ent, created_entry ? &freeent : NULL);
1704         if (err)
1705            goto done;
1706
1707         LOG(("fat_lookup_path(): %s/%s: %d\n", ent.short_filename, ent.long_filename, ent.dirent_sector_offset));
1708      }
1709      while(!ent.eof && mame_stricmp(path, ent.short_filename) && mame_stricmp(path, ent.long_filename));
1710
1711      parent_first_cluster = file->first_cluster;
1712
1713      if (ent.eof)
1714      {
1715         /* it seems that we have reached the end of this directory */
1716         if (!created_entry)
1717         {
1718            err = IMGTOOLERR_FILENOTFOUND;
1719            goto done;
1720         }
1721
1722         if (created_entry_len > FAT_DIRENT_SIZE)
1723         {
1724            /* must ensure uniqueness of the short filename */
1725            do
1726            {
1727               /* rewind to the beginning of the directory */
1728               err = fat_seek_file(partition, file, 0);
1729               if (err)
1730                  goto done;
1731
1732               bumped_sfn = FALSE;
1733               fat_cannonicalize_sfn(sfn, &created_entry[created_entry_len - FAT_DIRENT_SIZE]);
1734
1735               do
1736               {
1737                  err = fat_read_dirent(partition, file, &ent, NULL);
1738                  if (err)
1739                     goto done;
1740
1741                  if (!mame_stricmp(sfn, ent.short_filename))
1742                  {
1743                     bumped_sfn = TRUE;
1744                     fat_bump_dirent(partition, created_entry, created_entry_len);
1745                     fat_cannonicalize_sfn(sfn, &created_entry[created_entry_len - FAT_DIRENT_SIZE]);
1746                  }
1747               }
1748               while(!ent.eof);
1749            }
1750            while(bumped_sfn);
1751         }
1752
1753         LOG(("fat_lookup_path(): creating entry; pos=%u length=%u\n", freeent.position, freeent.required_size));
1754
1755         err = fat_set_file_size(partition, file, MAX(file->filesize, freeent.position + created_entry_len));
1756         if (err)
1757            goto done;
1758
1759         err = fat_seek_file(partition, file, freeent.position);
1760         if (err)
1761            goto done;
1762         
1763         err = fat_write_file(partition, file, created_entry, created_entry_len, NULL);
1764         if (err)
1765            goto done;
1766
1767         /* we have to do a special seek operation to get the main dirent */
1768         err = fat_seek_file(partition, file, freeent.position + created_entry_len - FAT_DIRENT_SIZE);
1769         if (err)
1770            goto done;
1771         entry_sector_index = fat_get_filepos_sector_index(partition, file);
1772         entry_sector_offset = file->index % FAT_SECLEN;
1773
1774         /* build the file struct for the newly created file/directory */
1775         memset(file, 0, sizeof(*file));
1776         file->directory = (created_entry[created_entry_len - FAT_DIRENT_SIZE + 11] & 0x10) ? 1 : 0;
1777         file->dirent_sector_index = entry_sector_index;
1778         file->dirent_sector_offset = entry_sector_offset;
1779      }
1780      else
1781      {
1782         /* update the current file */
1783         memset(file, 0, sizeof(*file));
1784         file->directory = ent.directory;
1785         file->filesize = ent.filesize;
1786         file->cluster = ent.first_cluster;
1787         file->first_cluster = ent.first_cluster;
1788         file->dirent_sector_index = ent.dirent_sector_index;
1789         file->dirent_sector_offset = ent.dirent_sector_offset;
1790      }
1791
1792      path = next_path_part;
1793      file->parent_first_cluster = parent_first_cluster;
1794   }
1795
1796   err = IMGTOOLERR_SUCCESS;
1797
1798done:
1799   if (created_entry)
1800      free(created_entry);
1801   return err;
1802}
1803
1804
1805
1806static imgtoolerr_t fat_partition_beginenum(imgtool_directory *enumeration, const char *path)
1807{
1808   imgtoolerr_t err;
1809   fat_file *file;
1810
1811   file = (fat_file *) imgtool_directory_extrabytes(enumeration);
1812
1813   err = fat_lookup_path(imgtool_directory_partition(enumeration), path, CREATE_NONE, file);
1814   if (err)
1815      return err;
1816   if (!file->directory)
1817      return IMGTOOLERR_PATHNOTFOUND;
1818   return IMGTOOLERR_SUCCESS;
1819}
1820
1821
1822
1823static imgtoolerr_t fat_partition_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
1824{
1825   imgtoolerr_t err;
1826   fat_file *file;
1827   fat_dirent fatent;
1828
1829   file = (fat_file *) imgtool_directory_extrabytes(enumeration);
1830   err = fat_read_dirent(imgtool_directory_partition(enumeration), file, &fatent, NULL);
1831   if (err)
1832      return err;
1833
1834   /* copy stuff from the FAT dirent to the Imgtool dirent */
1835   snprintf(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), "%s", fatent.long_filename[0]
1836      ? fatent.long_filename : fatent.short_filename);
1837   ent->filesize = fatent.filesize;
1838   ent->directory = fatent.directory;
1839   ent->eof = fatent.eof;
1840   ent->creation_time = fatent.creation_time;
1841   ent->lastmodified_time = fatent.lastmodified_time;
1842   return IMGTOOLERR_SUCCESS;
1843}
1844
1845
1846
1847static imgtoolerr_t fat_read_bootblock(imgtool_partition *partition, imgtool_stream *stream)
1848{
1849   imgtoolerr_t err;
1850   UINT8 block[FAT_SECLEN];
1851
1852   err = fat_read_sector(partition, 0, 0, block, sizeof(block));
1853   if (err)
1854      return err;
1855
1856   stream_write(stream, block, sizeof(block));
1857   return IMGTOOLERR_SUCCESS;
1858}
1859
1860
1861
1862static imgtoolerr_t fat_write_bootblock(imgtool_partition *partition, imgtool_stream *stream)
1863{
1864   imgtoolerr_t err;
1865   UINT8 block[FAT_SECLEN];
1866   UINT8 new_block[FAT_SECLEN];
1867
1868   if (stream_size(stream) != sizeof(new_block))
1869      return IMGTOOLERR_UNEXPECTED;
1870   stream_read(stream, new_block, sizeof(new_block));
1871
1872   if (new_block[510] != 0x55)
1873      return IMGTOOLERR_UNEXPECTED;
1874   if (new_block[511] != 0xAA)
1875      return IMGTOOLERR_UNEXPECTED;
1876
1877   /* read current boot sector */
1878   err = fat_read_sector(partition, 0, 0, block, sizeof(block));
1879   if (err)
1880      return err;
1881
1882   /* merge in the new stuff */
1883   memcpy(&block[ 0], &new_block[ 0],   3);
1884   memcpy(&block[62], &new_block[62], 448);
1885
1886   /* and write it out */
1887   err = fat_write_sector(partition, 0, 0, block, sizeof(block));
1888   if (err)
1889      return err;
1890
1891   return IMGTOOLERR_SUCCESS;
1892}
1893
1894
1895
1896static imgtoolerr_t fat_partition_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
1897{
1898   imgtoolerr_t err;
1899   fat_file file;
1900   size_t bytes_read;
1901   char buffer[1024];
1902
1903   /* special case for bootblock */
1904   if (filename == FILENAME_BOOTBLOCK)
1905      return fat_read_bootblock(partition, destf);
1906
1907   err = fat_lookup_path(partition, filename, CREATE_NONE, &file);
1908   if (err)
1909      return err;
1910
1911   if (file.directory)
1912      return IMGTOOLERR_FILENOTFOUND;
1913
1914   do
1915   {
1916      err = fat_read_file(partition, &file, buffer, sizeof(buffer), &bytes_read);
1917      if (err)
1918         return err;
1919
1920      stream_write(destf, buffer, bytes_read);
1921   }
1922   while(bytes_read > 0);
1923   return IMGTOOLERR_SUCCESS;
1924}
1925
1926
1927
1928static imgtoolerr_t fat_partition_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
1929{
1930   imgtoolerr_t err;
1931   fat_file file;
1932   UINT32 bytes_left, len;
1933   char buffer[1024];
1934
1935   /* special case for bootblock */
1936   if (filename == FILENAME_BOOTBLOCK)
1937      return fat_write_bootblock(partition, sourcef);
1938
1939   err = fat_lookup_path(partition, filename, CREATE_FILE, &file);
1940   if (err)
1941      return err;
1942
1943   if (file.directory)
1944      return IMGTOOLERR_FILENOTFOUND;
1945
1946   bytes_left = (UINT32) stream_size(sourcef);
1947
1948   err = fat_set_file_size(partition, &file, bytes_left);
1949   if (err)
1950      return err;
1951
1952   while(bytes_left > 0)
1953   {
1954      len = MIN(bytes_left, sizeof(buffer));
1955      stream_read(sourcef, buffer, len);
1956
1957      err = fat_write_file(partition, &file, buffer, len, NULL);
1958      if (err)
1959         return err;
1960
1961      bytes_left -= len;
1962   }
1963   return IMGTOOLERR_SUCCESS;
1964}
1965
1966
1967
1968static imgtoolerr_t fat_partition_delete(imgtool_partition *partition, const char *filename, unsigned int dir)
1969{
1970   imgtoolerr_t err;
1971   fat_file file;
1972   fat_dirent ent;
1973
1974   err = fat_lookup_path(partition, filename, CREATE_NONE, &file);
1975   if (err)
1976      return err;
1977   if (file.directory != dir)
1978      return IMGTOOLERR_FILENOTFOUND;
1979
1980   if (dir)
1981   {
1982      err = fat_read_dirent(partition, &file, &ent, NULL);
1983      if (err)
1984         return err;
1985      if (!ent.eof)
1986         return IMGTOOLERR_DIRNOTEMPTY;
1987   }
1988
1989   err = fat_set_file_size(partition, &file, ~0);
1990   if (err)
1991      return err;
1992
1993   return IMGTOOLERR_SUCCESS;
1994}
1995
1996
1997
1998static imgtoolerr_t fat_partition_deletefile(imgtool_partition *partition, const char *filename)
1999{
2000   return fat_partition_delete(partition, filename, 0);
2001}
2002
2003
2004
2005static imgtoolerr_t fat_partition_freespace(imgtool_partition *partition, UINT64 *size)
2006{
2007   imgtoolerr_t err;
2008   const fat_partition_info *disk_info;
2009   UINT8 *fat_table;
2010   UINT32 i;
2011
2012   disk_info = fat_get_partition_info(partition);
2013
2014   err = fat_load_fat(partition, &fat_table);
2015   if (err)
2016      goto done;
2017
2018   *size = 0;
2019   for (i = 2; i < disk_info->total_clusters; i++)
2020   {
2021      if (fat_get_fat_entry(partition, fat_table, i) == 0)
2022         *size += disk_info->cluster_size;
2023   }
2024
2025done:
2026   if (fat_table)
2027      free(fat_table);
2028   return err;
2029}
2030
2031
2032
2033static imgtoolerr_t fat_partition_createdir(imgtool_partition *partition, const char *path)
2034{
2035   imgtoolerr_t err;
2036   fat_file file;
2037   UINT8 initial_data[64];
2038
2039   err = fat_lookup_path(partition, path, CREATE_DIR, &file);
2040   if (err)
2041      return err;
2042   if (!file.directory)
2043      return IMGTOOLERR_FILENOTFOUND;
2044
2045   err = fat_set_file_size(partition, &file, sizeof(initial_data));
2046   if (err)
2047      return err;
2048
2049   /* set up the two directory entries in all directories */
2050   memset(initial_data, 0, sizeof(initial_data));
2051   memcpy(&initial_data[0], ".          ", 11);
2052   place_integer_le(initial_data, 11, 1, 0x10);
2053   place_integer_le(initial_data, 26, 2, file.first_cluster);
2054   memcpy(&initial_data[32], ".          ", 11);
2055   place_integer_le(initial_data, 43, 1, 0x10);
2056   place_integer_le(initial_data, 58, 2, file.parent_first_cluster);
2057
2058   err = fat_write_file(partition, &file, initial_data, sizeof(initial_data), NULL);
2059   if (err)
2060      return err;
2061
2062   return IMGTOOLERR_SUCCESS;
2063}
2064
2065
2066
2067static imgtoolerr_t fat_partition_deletedir(imgtool_partition *partition, const char *path)
2068{
2069   return fat_partition_delete(partition, path, 1);
2070}
2071
2072
2073
2074void fat_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
2075{
2076   switch(state)
2077   {
2078      /* --- the following bits of info are returned as 64-bit signed integers --- */
2079      case IMGTOOLINFO_INT_INITIAL_PATH_SEPARATOR:      info->i = 1; break;
2080      case IMGTOOLINFO_INT_OPEN_IS_STRICT:            info->i = 1; break;
2081      case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME:      info->i = 1; break;
2082      case IMGTOOLINFO_INT_SUPPORTS_LASTMODIFIED_TIME:   info->i = 1; break;
2083      case IMGTOOLINFO_INT_SUPPORTS_BOOTBLOCK:         info->i = 1; break;
2084      case IMGTOOLINFO_INT_PATH_SEPARATOR:            info->i = '\\'; break;
2085      case IMGTOOLINFO_INT_ALTERNATE_PATH_SEPARATOR:      info->i = '/'; break;
2086      case IMGTOOLINFO_INT_PARTITION_EXTRA_BYTES:         info->i = sizeof(fat_partition_info); break;
2087      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:         info->i = sizeof(fat_file); break;
2088
2089      /* --- the following bits of info are returned as NULL-terminated strings --- */
2090      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
2091      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r\n"); break;
2092
2093      /* --- the following bits of info are returned as pointers to data or functions --- */
2094      case IMGTOOLINFO_PTR_CREATE_PARTITION:            info->create_partition = fat_partition_create; break;
2095      case IMGTOOLINFO_PTR_OPEN_PARTITION:            info->open_partition = fat_partition_open; break;
2096      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = fat_partition_beginenum; break;
2097      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = fat_partition_nextenum; break;
2098      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = fat_partition_readfile; break;
2099      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = fat_partition_writefile; break;
2100      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = fat_partition_deletefile; break;
2101      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = fat_partition_freespace; break;
2102      case IMGTOOLINFO_PTR_CREATE_DIR:               info->create_dir = fat_partition_createdir; break;
2103      case IMGTOOLINFO_PTR_DELETE_DIR:               info->delete_dir = fat_partition_deletedir; break;
2104   }
2105}
src/mess/tools/imgtool/modules/cococas.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6#include "formats/cococas.h"
7#include "utils.h"
8
9static int cococas_initalt(imgtool_stream *instream, imgtool_stream **outstream, int *basepos,
10   int *length, int *channels, int *frequency, int *resolution);
11static int cococas_nextfile(imgtool_image *img, imgtool_dirent *ent);
12static int cococas_readfile(imgtool_image *img, imgtool_stream *destf);
13
14static UINT8 blockheader[] = { 0x55, 0x3C };
15
16WAVEMODULE(
17   cococas,
18   "Tandy CoCo Cassette",
19   "wav",
20   "\r",
21   IMGMODULE_FLAG_FILENAMES_PREFERUCASE,
22   1200, 1600, 2400,                  /* 0=1200 Hz, 1=2400 Hz, threshold=1600 Hz */
23   WAVEIMAGE_LSB_FIRST,
24   blockheader, sizeof(blockheader) / sizeof(blockheader[0]),
25   cococas_initalt,                  /* alternate initializer */
26   cococas_nextfile,                  /* enumerate next */
27   cococas_readfile                  /* read file */
28)
29
30typedef struct {
31   UINT8 type;
32   UINT8 length;
33   UINT8 data[255];
34} casblock;
35
36enum {
37   COCOCAS_FILETYPE_BASIC = 0,
38   COCOCAS_FILETYPE_DATA = 1,
39   COCOCAS_FILETYPE_BIN = 2
40};
41
42enum {
43   COCOCAS_BLOCKTYPE_FILENAME = 0,
44   COCOCAS_BLOCKTYPE_DATA = 1,
45   COCOCAS_BLOCKTYPE_EOF = 0xff
46};
47
48static int readblock(imgtool_image *img, casblock *blk)
49{
50   int err;
51   int i;
52   UINT8 sum = 0;
53   UINT8 actualsum;
54
55   /* Move forward until we hit header */
56   err = imgwave_forward(img);
57   if (err)
58      return err;
59
60   /* Read in the block type and length */
61   err = imgwave_read(img, &blk->type, 2);
62   if (err)
63      return err;
64   sum += blk->type;
65   sum += blk->length;
66
67   /* Read in the block data */
68   err = imgwave_read(img, blk->data, blk->length);
69   if (err)
70      return err;
71
72   /* Calculate checksum */
73   for (i = 0; i < blk->length; i++)
74      sum += blk->data[i];
75
76   /* Read the checksum */
77   err = imgwave_read(img, &actualsum, 1);
78   if (err)
79      return err;
80
81   if (sum != actualsum)
82      return IMGTOOLERR_CORRUPTIMAGE;
83
84   return 0;
85}
86
87static int cococas_nextfile(imgtool_image *img, imgtool_dirent *ent)
88{
89   int err, filesize;
90   casblock blk;
91   char fname[9];
92
93   /* Read directory block */
94   err = readblock(img, &blk);
95   if (err == IMGTOOLERR_INPUTPASTEND) {
96      ent->eof = 1;
97      return 0;
98   }
99   if (err)
100      return err;
101   
102   /* If block is not a filename block, fail */
103   if (blk.type != COCOCAS_BLOCKTYPE_FILENAME)
104      return IMGTOOLERR_CORRUPTIMAGE;
105
106   fname[8] = '\0';
107   memcpy(fname, blk.data, 8);
108   rtrim(fname);
109
110   if (strlen(fname) >= ent->fname_len)
111      return IMGTOOLERR_BUFFERTOOSMALL;
112   strcpy(ent->fname, fname);
113
114   filesize = 0;
115
116   do {
117      err = readblock(img, &blk);
118      if (err)
119         return err;
120
121      if (blk.type == COCOCAS_BLOCKTYPE_DATA) {
122         filesize += blk.length;
123      }
124   }
125   while(blk.type == COCOCAS_BLOCKTYPE_DATA);
126
127   if (blk.type != COCOCAS_BLOCKTYPE_EOF)
128      return IMGTOOLERR_CORRUPTIMAGE;
129   
130   ent->filesize = filesize;
131
132   return 0;
133}
134
135static int cococas_readfile(imgtool_image *img, imgtool_stream *destf)
136{
137   int err;
138   casblock blk;
139
140   /* Read directory block */
141   err = readblock(img, &blk);
142   if (err)
143      return err;
144   
145   /* If block is not a filename block, fail */
146   if (blk.type != COCOCAS_BLOCKTYPE_FILENAME)
147      return IMGTOOLERR_CORRUPTIMAGE;
148
149   do {
150      err = readblock(img, &blk);
151      if (err)
152         return err;
153
154      if (blk.type == COCOCAS_BLOCKTYPE_DATA)
155         stream_write(destf, blk.data, blk.length);
156   }
157   while(blk.type == COCOCAS_BLOCKTYPE_DATA);
158
159   if (blk.type != COCOCAS_BLOCKTYPE_EOF)
160      return IMGTOOLERR_CORRUPTIMAGE;
161   
162   return 0;
163}
164
165static int cococas_initalt(imgtool_stream *instream, imgtool_stream **outstream, int *basepos,
166   int *length, int *channels, int *frequency, int *resolution)
167{
168   int caslength;
169   int numsamples;
170   int samplepos;
171   UINT8 *bytes = NULL;
172   INT16 *buffer = NULL;
173   INT16 *newbuffer;
174
175   caslength = stream_size(instream);
176   bytes = malloc(caslength);
177   if (!bytes)
178      goto outofmemory;
179   stream_read(instream, bytes, caslength);
180
181   numsamples = COCO_WAVESAMPLES_HEADER + COCO_WAVESAMPLES_TRAILER + (caslength * 8*8);
182
183   buffer = malloc(numsamples * sizeof(INT16));
184   if (!buffer)
185      goto outofmemory;
186
187   coco_wave_size = caslength;
188
189   samplepos = 0;
190   samplepos += coco_cassette_fill_wave(&buffer[samplepos], COCO_WAVESAMPLES_HEADER, CODE_HEADER);
191   samplepos += coco_cassette_fill_wave(&buffer[samplepos], caslength, bytes);
192   samplepos += coco_cassette_fill_wave(&buffer[samplepos], COCO_WAVESAMPLES_TRAILER, CODE_TRAILER);
193
194   free(bytes);
195   bytes = NULL;
196
197   newbuffer = realloc(buffer, samplepos * sizeof(INT16));
198   if (!newbuffer)
199      goto outofmemory;
200   buffer = newbuffer;
201
202   *outstream = stream_open_mem(buffer, samplepos * sizeof(INT16));
203   if (!(*outstream))
204      goto outofmemory;
205
206   *basepos = 0;
207   *length = samplepos * 2;
208   *channels = 1;
209   *frequency = 4800;
210   *resolution = 16;
211   return 0;
212
213outofmemory:
214   if (bytes)
215      free(bytes);
216   if (buffer)
217      free(buffer);
218   return IMGTOOLERR_OUTOFMEMORY;
219}
220
221
222
src/mess/tools/imgtool/modules/t64.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6
7#ifdef LSB_FIRST
8typedef UINT16 littleuword;
9typedef UINT32 littleulong;
10#define GET_UWORD(a) a
11#define GET_ULONG(a) a
12#define SET_UWORD(a,v) a=v
13#define SET_ULONG(a,v) a=v
14#else
15typedef struct {
16   unsigned char low, high;
17} littleuword;
18typedef struct {
19   unsigned char low, mid, high, highest;
20} littleulong;
21#define GET_UWORD(a) (a.low|(a.high<<8))
22#define GET_ULONG(a) (a.low|(a.mid<<8)|(a.high<<16)|(a.highest<<24))
23#define SET_UWORD(a,v) a.low=(v)&0xff;a.high=((v)>>8)&0xff
24#define SET_ULONG(a,v) a.low=(v)&0xff;a.mid=((v)>>8)&0xff;a.high=((v)>>16)&0xff;a.highest=((v)>>24)&0xff
25#endif
26
27/*
28T64 File Structure was developed by Miha Peternel for use in C64S.
29It is easy to use and allows future extensions.
30
31______________________
32  T64 file structure
33
34  Offset, size, description
35       0, 64    tape record
36      64, 32*n  file records for n directory entries
37 64+32*n, ???   binary contents of the files
38
39_______________
40  Tape Record
41
42  Offset, size, description
43       0, 32    DOS tape description + EOF (for type)
44      32, 2     tape version ($0101)
45      34, 2     number of directory entries
46      36, 2     number of used entries (can be 0 in my loader)
47      38, 2     free
48      40, 24    user description as displayed in tape menu
49
50_______________
51  File Record
52
53  Offset, size, description
54       0, 1     entry type
55                0 = free entry
56                1 = normal tape file
57                3 = memory snapshot v0.9, uncompressed
58                2..255 reserved (for memory snapshots...)
59       1, 1     C64 file type
60       2, 2     start address
61       4, 2     end address
62       6, 2     free
63       8, 4     offset of file contents start within T64 file
64      12, 4     free
65      16, 16    C64 file name
66
67*/
68 
69typedef struct{
70   char dostext[0x20]; // dos text
71   littleuword version; // packed bcd
72   littleuword max_entries;
73   littleuword used_entries;
74   littleuword reserved;
75   char description[24];
76} t64_header;
77   
78typedef struct {
79   unsigned char type;
80   unsigned char file_type;
81   littleuword start_address;
82   littleuword end_address;
83   littleuword reserved;
84   littleulong offset;
85   littleulong reserved2;
86   char name[0x10];
87} t64_entry;
88
89typedef struct {
90   imgtool_image base;
91   imgtool_stream *file_handle;
92   int size;
93   int modified;
94   unsigned char *data;
95} t64_image;
96
97#define HEADER(image) ((t64_header*)image->data)
98#define ENTRY(image, index) ((t64_entry*)(image->data+sizeof(t64_header))+index)
99
100typedef struct {
101   imgtool_directory base;
102   t64_image *image;
103   int index;
104} t64_iterator;
105
106static int t64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
107static void t64_image_exit(imgtool_image *img);
108static void t64_image_info(imgtool_image *img, char *string, const int len);
109static int t64_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
110static int t64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
111static void t64_image_closeenum(imgtool_directory *enumeration);
112//static size_t t64_image_freespace(imgtool_image *img);
113static int t64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
114static int t64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *_options);
115static int t64_image_deletefile(imgtool_image *img, const char *fname);
116static int t64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options);
117
118static struct OptionTemplate t64_createopts[] =
119{
120   { "entries", NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      3,      NULL   },   /* [0] */
121   { "label", NULL, IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,   0,      0,      NULL   },   /* [1] */
122   { NULL, NULL, 0, 0, 0, 0 }
123};
124
125#define T64_OPTION_ENTRIES   0
126#define T64_OPTION_LABEL   1
127
128IMAGEMODULE(
129   t64,
130   "Commodore 64 Archive for Tapes",   /* human readable name */
131   "t64",                        /* file extension */
132   NULL,                        /* crcfile */
133   NULL,                        /* crc system name */
134   EOLN_CR,                     /* eoln */
135   0,                           /* flags */
136   t64_image_init,                  /* init function */
137   t64_image_exit,                  /* exit function */
138   t64_image_info,                  /* info function */
139   t64_image_beginenum,            /* begin enumeration */
140   t64_image_nextenum,               /* enumerate next */
141   t64_image_closeenum,            /* close enumeration */
142   NULL, //t64_image_freespace,      /* free space on image */
143   t64_image_readfile,               /* read file */
144   t64_image_writefile,            /* write file */
145   t64_image_deletefile,            /* delete file */
146   t64_image_create,               /* create image */
147   NULL,                        /* read sector */
148   NULL,                        /* write sector */
149   NULL,                        /* file _options */
150   t64_createopts                  /* create options */
151)
152
153static int t64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
154{
155   t64_image *image;
156
157   image=*(t64_image**)outimg=(t64_image *) malloc(sizeof(t64_image));
158   if (!image) return IMGTOOLERR_OUTOFMEMORY;
159
160   memset(image, 0, sizeof(t64_image));
161   image->base.module = mod;
162   image->size=stream_size(f);
163   image->file_handle=f;
164
165   image->data = (unsigned char *) malloc(image->size);
166   if ( (!image->data)
167       ||(stream_read(f, image->data, image->size)!=image->size) ) {
168      free(image);
169      *outimg=NULL;
170      return IMGTOOLERR_OUTOFMEMORY;
171   }
172
173   return 0;
174}
175
176static void t64_image_exit(imgtool_image *img)
177{
178   t64_image *image=(t64_image*)img;
179   if (image->modified) {
180      stream_clear(image->file_handle);
181      stream_write(image->file_handle, image->data, image->size);
182   }
183   stream_close(image->file_handle);
184   free(image->data);
185   free(image);
186}
187
188static void t64_image_info(imgtool_image *img, char *string, const int len)
189{
190   t64_image *image=(t64_image*)img;
191   char dostext_with_null[33]= { 0 };
192   char name_with_null[25]={ 0 };
193   strncpy(dostext_with_null, HEADER(image)->dostext, 32);
194   strncpy(name_with_null, HEADER(image)->description, 24);
195   sprintf(string,"%s\n%s\nversion:%.4x max entries:%d",
196         dostext_with_null,
197         name_with_null,
198         GET_UWORD(HEADER(image)->version),
199         HEADER(image)->max_entries);
200}
201
202static int t64_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
203{
204   t64_image *image=(t64_image*)img;
205   t64_iterator *iter;
206
207   iter=*(t64_iterator**)outenum = (t64_iterator *) malloc(sizeof(t64_iterator));
208   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
209
210   iter->base.module = img->module;
211
212   iter->image=image;
213   iter->index = 0;
214   return 0;
215}
216
217static int t64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
218{
219   t64_iterator *iter=(t64_iterator*)enumeration;
220   ent->corrupt=0;
221   
222   for (;!(ent->eof=(iter->index>=GET_UWORD(HEADER(iter->image)->max_entries)));iter->index++ ){
223      if (ENTRY(iter->image, iter->index)->type==0) continue;
224      memset(ent->fname,0,17);
225      strncpy(ent->fname, ENTRY(iter->image, iter->index)->name, 16);
226      if (ent->attr)
227         sprintf(ent->attr,"start:%.4x end:%.4x type:%d file:%d",
228               GET_UWORD( ENTRY(iter->image,iter->index)->start_address),
229               GET_UWORD( ENTRY(iter->image,iter->index)->end_address),
230               ENTRY(iter->image,iter->index)->type,
231               ENTRY(iter->image,iter->index)->file_type );
232      ent->filesize=GET_UWORD( ENTRY(iter->image, iter->index)->end_address )
233         -GET_UWORD( ENTRY(iter->image, iter->index)->start_address );
234      iter->index++;
235      break;
236   }
237   return 0;
238}
239
240static void t64_image_closeenum(imgtool_directory *enumeration)
241{
242   free(enumeration);
243}
244
245#if 0
246static size_t t64_image_freespace(imgtool_image *img)
247{
248   int i;
249   rsdos_diskimage *rsimg = (rsdos_diskimage *) img;
250   size_t s = 0;
251
252   for (i = 0; i < GRANULE_COUNT; i++)
253      if (rsimg->granulemap[i] == 0xff)
254         s += (9 * 256);
255   return s;
256}
257#endif
258
259static int t64_image_findfile(t64_image *image, const char *fname)
260{
261   int i=0;
262
263   for (i=0; i<GET_UWORD(HEADER(image)->max_entries); i++) {
264      if (ENTRY(image, i)->type==0) continue;
265      if (!strnicmp(fname, ENTRY(image,i)->name, strlen(fname)) ) return i;
266   }
267   return -1;
268}
269
270static int t64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
271{
272   t64_image *image=(t64_image*)img;
273   int size;
274   int ind;
275
276   if ((ind=t64_image_findfile(image, fname))==-1 ) return IMGTOOLERR_MODULENOTFOUND;
277
278   size=GET_UWORD( ENTRY(image, ind)->end_address )-GET_UWORD( ENTRY(image, ind)->start_address );
279
280   if (stream_write(destf, &ENTRY(image, ind)->start_address, 2)!=2) {
281      return IMGTOOLERR_WRITEERROR;
282   }
283   if (stream_write(destf, image->data+GET_ULONG(ENTRY(image, ind)->offset), size)!=size) {
284      return IMGTOOLERR_WRITEERROR;
285   }
286
287   return 0;
288}
289
290static int t64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *_options)
291{
292   t64_image *image=(t64_image*)img;
293   int size, fsize;
294   int ind;
295   int pos, i, t;
296
297   fsize=stream_size(sourcef);
298   if ((ind=t64_image_findfile(image, fname))==-1 ) {
299      // appending
300      for (ind=0; ind<GET_UWORD(HEADER(image)->max_entries)&&(ENTRY(image,ind)->type!=0); ind++) ;
301      if (ind>=GET_UWORD(HEADER(image)->max_entries)) return IMGTOOLERR_NOSPACE;
302      pos=image->size;
303      if (!(image->data=realloc(image->data, image->size+fsize-2)) )
304         return IMGTOOLERR_OUTOFMEMORY;
305      image->size+=fsize-2;
306#ifdef LSB_FIRST
307      HEADER(image)->used_entries++;
308#else
309      if (++HEADER(image)->used_entries.low == 0)
310         HEADER(image)->used_entries.high++;
311#endif
312   } else {
313      pos=GET_ULONG(ENTRY(image,ind)->offset);
314      // find the size of the data in this area
315      for (size=image->size-pos, i=0; i<GET_UWORD(HEADER(image)->max_entries); i++) {
316         if (ENTRY(image,i)->type==0) continue;
317         if (GET_UWORD(ENTRY(image,i)->offset)<pos) continue;
318         if (GET_ULONG(ENTRY(image,i)->offset)-pos>=size) continue;
319         size=GET_ULONG(ENTRY(image, i)->offset)-pos;
320      }
321      if ((size!=0)&&(image->size-pos-size!=0))
322         memmove(image->data+pos, image->data+pos+size, image->size-pos-size);
323      // correct offset positions in other entries
324      for (i=0;i<GET_UWORD(HEADER(image)->max_entries); i++) {
325         if (i==ind) continue;
326         if (ENTRY(image,i)->type==0) continue;
327         if (GET_ULONG(ENTRY(image,i)->offset)<pos) continue;
328         t=GET_ULONG(ENTRY(image,i)->offset)-size;
329         SET_ULONG( ENTRY(image,i)->offset, t);
330      }
331      // overwritting
332      if (!(image->data=realloc(image->data, image->size+fsize-2-size)))
333         return IMGTOOLERR_OUTOFMEMORY;
334      pos=image->size;
335      image->size=image->size+fsize-2-size;
336   }
337   memset(ENTRY(image,ind), 0, sizeof(t64_entry));
338   if (stream_read(sourcef, &ENTRY(image,ind)->start_address, 2)!=2) {
339      return IMGTOOLERR_READERROR;
340   }
341   if (stream_read(sourcef, image->data+pos, fsize-2)!=fsize-2) {
342      return IMGTOOLERR_READERROR;
343   }
344   SET_UWORD( ENTRY(image, ind)->end_address,
345            GET_UWORD( ENTRY(image, ind)->start_address)+fsize-2);
346   SET_ULONG( ENTRY(image, ind)->offset, pos);
347   strncpy(ENTRY(image, ind)->name, fname, 16);
348   ENTRY(image,ind)->type=1; // normal file
349   ENTRY(image,ind)->file_type=1; // prg
350   image->modified=1;
351
352   return 0;
353}
354
355static int t64_image_deletefile(imgtool_image *img, const char *fname)
356{
357   t64_image *image=(t64_image*)img;
358   int pos, size;
359   int ind, i;
360
361   if ((ind=t64_image_findfile(image, fname))==-1 ) {
362      return IMGTOOLERR_MODULENOTFOUND;
363   }
364   pos=GET_ULONG(ENTRY(image,ind)->offset);
365   // find the size of the data in this area
366   for (size=image->size-pos, i=0; i<GET_UWORD(HEADER(image)->max_entries); i++) {
367      if (ENTRY(image,i)->type==0) continue;
368      if (GET_UWORD(ENTRY(image,i)->offset)<pos) continue;
369      if (GET_ULONG(ENTRY(image,i)->offset)-pos>=size) continue;
370      size=GET_ULONG(ENTRY(image, i)->offset)-pos;
371   }
372   if ((size!=0)&&(image->size-pos-size!=0))
373      memmove(image->data+pos, image->data+pos+size, image->size-pos-size);
374   // correct offset positions in other entries
375   for (i=0;i<GET_UWORD(HEADER(image)->max_entries); i++) {
376      if (i==ind) continue;
377      if (ENTRY(image,i)->type==0) continue;
378      if (GET_ULONG(ENTRY(image,i)->offset)<pos) continue;
379      SET_ULONG( ENTRY(image,i)->offset, GET_ULONG(ENTRY(image,i)->offset)-size );
380   }
381   image->size-=size;
382   ENTRY(image,ind)->type=0; // normal file
383   image->modified=1;
384#ifdef LSB_FIRST
385   HEADER(image)->used_entries--;
386#else
387      if (HEADER(image)->used_entries.low-- == 0)
388         HEADER(image)->used_entries.high--;
389#endif
390
391   return 0;
392}
393
394static int t64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options)
395{
396   int entries;
397   t64_header header={ "T64 Tape archiv created by MESS\x1a" };
398   t64_entry entry= { 0 };
399   int i;
400
401   entries = _options[T64_OPTION_ENTRIES].i;
402   if (entries==0) entries=10;
403   SET_UWORD(header.version, 0x0101);
404   SET_UWORD(header.max_entries, entries);
405   if (_options[T64_OPTION_LABEL].s) strcpy(header.description, _options[T64_OPTION_LABEL].s);
406   if (stream_write(f, &header, sizeof(t64_header)) != sizeof(t64_header))
407      return  IMGTOOLERR_WRITEERROR;
408   for (i=0; i<entries; i++) {
409   if (stream_write(f, &entry, sizeof(t64_entry)) != sizeof(t64_entry))
410      return  IMGTOOLERR_WRITEERROR;
411   }
412
413   return 0;
414}
415
src/mess/tools/imgtool/modules/cybiko.c
r0r1340
1/*
2
3   Cybiko File System
4
5   (c) 2007 Tim Schuerewegen
6
7*/
8
9#include "imgtool.h"
10
11#include <zlib.h>
12
13#ifndef FALSE
14#    define FALSE 0
15#endif
16#ifndef TRUE
17#    define TRUE (!FALSE)
18#endif
19
20typedef struct _cybiko_file_system cybiko_file_system;
21struct _cybiko_file_system
22{
23   imgtool_stream *stream;
24   UINT32 page_count, page_size, block_count_boot, block_count_file;
25   UINT16 write_count;
26};
27
28typedef struct _cybiko_iter cybiko_iter;
29struct _cybiko_iter
30{
31   UINT16 block;
32};
33
34typedef struct _cfs_file cfs_file;
35struct _cfs_file
36{
37   char name[64]; // name of the file
38   UINT32 date;   // date/time of the file (seconds since 1900/01/01)
39   UINT32 size;   // size of the file
40   UINT32 blocks; // number of blocks occupied by the file
41};
42
43enum
44{
45   BLOCK_TYPE_INVALID,
46   BLOCK_TYPE_BOOT,
47   BLOCK_TYPE_FILE
48};
49
50#define   MAX_PAGE_SIZE (264 * 2)
51
52#define INVALID_FILE_ID  0xFFFF
53
54enum
55{
56   FLASH_TYPE_INVALID,
57   FLASH_TYPE_AT45DB041,
58   FLASH_TYPE_AT45DB081,
59   FLASH_TYPE_AT45DB161
60};
61
62#define BLOCK_USED(x)      (x[0] & 0x80)
63#define BLOCK_FILE_ID(x)   buffer_read_16_be( x + 2)
64#define BLOCK_PART_ID(x)   buffer_read_16_be( x + 4)
65#define BLOCK_FILENAME(x)  (char*)(x + 7)
66
67#define FILE_HEADER_SIZE  0x48
68
69// 2208988800 is the number of seconds between 1900/01/01 and 1970/01/01
70
71static time_t time_crack( UINT32 cfs_time)
72{
73   return (time_t)(cfs_time - 2208988800UL);
74}
75
76static UINT32 time_setup( time_t ansi_time)
77{
78   return (UINT32)(ansi_time + 2208988800UL);
79}
80
81static UINT32 buffer_read_32_be( UINT8 *buffer)
82{
83   return (buffer[0] << 24) | (buffer[1] << 16) | (buffer[2] << 8) | (buffer[3] << 0);
84}
85
86static UINT16 buffer_read_16_be( UINT8 *buffer)
87{
88   return (buffer[0] << 8) | (buffer[1] << 0);
89}
90
91static void buffer_write_32_be( UINT8 *buffer, UINT32 data)
92{
93   buffer[0] = (data >> 24) & 0xFF;
94   buffer[1] = (data >> 16) & 0xFF;
95   buffer[2] = (data >>  8) & 0xFF;
96   buffer[3] = (data >>  0) & 0xFF;
97}
98
99static void buffer_write_16_be( UINT8 *buffer, UINT16 data)
100{
101   buffer[0] = (data >> 8) & 0xFF;
102   buffer[1] = (data >> 0) & 0xFF;
103}
104
105// page = crc1 (4) + wcnt (2) + crc2 (2) + data (x) + unk (2)
106
107static UINT32 page_buffer_calc_checksum_1( UINT8 *buffer, UINT32 size, int block_type)
108{
109   return crc32( 0, buffer + 8, (block_type == BLOCK_TYPE_BOOT) ? 250 : size - 10);
110}
111
112static UINT16 page_buffer_calc_checksum_2( UINT8 *buffer)
113{
114   UINT16 val = 0xAF17;
115   val ^= buffer_read_16_be( buffer + 0);
116   val ^= buffer_read_16_be( buffer + 2);
117   val ^= buffer_read_16_be( buffer + 4);
118   return FLIPENDIAN_INT16(val);
119}
120
121static int page_buffer_verify( UINT8 *buffer, UINT32 size, int block_type)
122{
123   UINT32 checksum_page, checksum_calc;
124   // checksum 1
125   checksum_calc = page_buffer_calc_checksum_1( buffer, size, block_type);
126   checksum_page = buffer_read_32_be( buffer + 0);
127   if (checksum_calc != checksum_page) return FALSE;
128   // checksum 2
129   checksum_calc = page_buffer_calc_checksum_2( buffer);
130   checksum_page = buffer_read_16_be( buffer + 6);
131   if (checksum_calc != checksum_page) return FALSE;
132   // ok
133   return TRUE;
134}
135
136static int cfs_block_to_page( cybiko_file_system *cfs, int block_type, UINT32 block, UINT32 *page)
137{
138   switch (block_type)
139   {
140      case BLOCK_TYPE_BOOT : if (page) *page = block; return TRUE;
141      case BLOCK_TYPE_FILE : if (page) *page = block + cfs->block_count_boot; return TRUE;
142      default              : return FALSE;
143   }
144}
145
146static int cfs_page_to_block( cybiko_file_system *cfs, UINT32 page, int *block_type, UINT32 *block)
147{
148   UINT32 tmp = page;
149   // boot block
150   if (tmp < cfs->block_count_boot)
151   {
152      if (block_type) *block_type = BLOCK_TYPE_BOOT;
153      if (block) *block = tmp;
154      return TRUE;
155   }
156   tmp -= cfs->block_count_boot;
157   // file block
158   if (tmp < cfs->block_count_file)
159   {
160      if (block_type) *block_type = BLOCK_TYPE_FILE;
161      if (block) *block = tmp;
162      return TRUE;
163   }
164   tmp -= cfs->block_count_file;
165   // error
166   return FALSE;
167}
168
169static int cfs_page_read( cybiko_file_system *cfs, UINT8 *buffer, UINT32 page)
170{
171   if (page >= cfs->page_count) return FALSE;
172   stream_seek( cfs->stream, page * cfs->page_size, SEEK_SET);
173   stream_read( cfs->stream, buffer, cfs->page_size);
174   return TRUE;
175}
176
177static int cfs_page_write( cybiko_file_system *cfs, UINT8 *buffer, UINT32 page)
178{
179   if (page >= cfs->page_count) return FALSE;
180   stream_seek( cfs->stream, page * cfs->page_size, SEEK_SET);
181   stream_write( cfs->stream, buffer, cfs->page_size);
182   return TRUE;
183}
184
185static int cfs_block_read( cybiko_file_system *cfs, UINT8 *buffer, int block_type, UINT32 block)
186{
187   UINT8 buffer_page[MAX_PAGE_SIZE];
188   UINT32 page;
189   if (!cfs_block_to_page( cfs, block_type, block, &page)) return FALSE;
190   if (!cfs_page_read( cfs, buffer_page, page)) return FALSE;
191   memcpy( buffer, buffer_page + 8, cfs->page_size - 10);
192   return TRUE;
193}
194
195static int cfs_block_write( cybiko_file_system *cfs, UINT8 *buffer, int block_type, UINT32 block)
196{
197   UINT8 buffer_page[MAX_PAGE_SIZE];
198   UINT32 page;
199   memcpy( buffer_page + 8, buffer, cfs->page_size - 10);
200   buffer_write_32_be( buffer_page + 0, page_buffer_calc_checksum_1( buffer_page, cfs->page_size, block_type));
201   buffer_write_16_be( buffer_page + 4, cfs->write_count++);
202   buffer_write_16_be( buffer_page + 6, page_buffer_calc_checksum_2( buffer_page));
203   buffer_write_16_be( buffer_page + cfs->page_size - 2, 0xFFFF);
204   if (!cfs_block_to_page( cfs, block_type, block, &page)) return FALSE;
205   if (!cfs_page_write( cfs, buffer_page, page)) return FALSE;
206   return TRUE;
207}
208
209static int cfs_file_delete( cybiko_file_system *cfs, UINT16 file_id)
210{
211   UINT8 buffer[MAX_PAGE_SIZE];
212   int i;
213   for (i=0;i<cfs->block_count_file;i++)
214   {
215      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
216      if (BLOCK_USED(buffer) && (BLOCK_FILE_ID(buffer) == file_id))
217      {
218         buffer[0] &= ~0x80;
219         if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
220      }
221   }
222   return TRUE;
223}
224
225static int cfs_file_info( cybiko_file_system *cfs, UINT16 file_id, cfs_file *file)
226{
227   UINT8 buffer[MAX_PAGE_SIZE];
228   int i;
229   file->blocks = file->size = 0;
230   for (i=0;i<cfs->block_count_file;i++)
231   {
232      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
233      if (BLOCK_USED(buffer) && (BLOCK_FILE_ID(buffer) == file_id))
234      {
235         if (BLOCK_PART_ID(buffer) == 0)
236         {
237            strcpy( file->name, BLOCK_FILENAME(buffer));
238            file->date = buffer_read_32_be( buffer + 6 + FILE_HEADER_SIZE - 4);
239         }
240         file->size += buffer[1];
241         file->blocks++;
242      }
243   }
244   return (file->blocks > 0) ? TRUE : FALSE;
245}
246
247static int cfs_file_find( cybiko_file_system *cfs, const char *filename, UINT16 *file_id)
248{
249   UINT8 buffer[MAX_PAGE_SIZE];
250   int i;
251   for (i=0;i<cfs->block_count_file;i++)
252   {
253      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
254      if (BLOCK_USED(buffer) && (strncmp( filename, BLOCK_FILENAME(buffer), 40) == 0))
255      {
256         *file_id = i;
257         return TRUE;
258      }
259   }
260   return FALSE;
261}
262
263static int cfs_verify( cybiko_file_system *cfs)
264{
265   UINT8 buffer[MAX_PAGE_SIZE];
266   int i, block_type;
267   for (i=0;i<cfs->page_count;i++)
268   {
269      if (!cfs_page_read( cfs, buffer, i)) return FALSE;
270      if (!cfs_page_to_block( cfs, i, &block_type, NULL)) return FALSE;
271      if (!page_buffer_verify( buffer, cfs->page_size, block_type)) return FALSE;
272   }
273   return TRUE;
274}
275
276static int cfs_init( cybiko_file_system *cfs, imgtool_stream *stream, int flash_type)
277{
278   cfs->stream = stream;
279   switch (flash_type)
280   {
281      case FLASH_TYPE_AT45DB041 : cfs->page_count = 2048; cfs->page_size = 264; break;
282      case FLASH_TYPE_AT45DB081 : cfs->page_count = 4096; cfs->page_size = 264; break;
283      case FLASH_TYPE_AT45DB161 : cfs->page_count = 4096; cfs->page_size = 528; break;
284      default                   : return FALSE;
285   }
286   cfs->block_count_boot = 5;
287   cfs->block_count_file = cfs->page_count - cfs->block_count_boot;
288   cfs->write_count = 0;
289   return TRUE;
290}
291
292static int cfs_format( cybiko_file_system *cfs)
293{
294   UINT8 buffer[MAX_PAGE_SIZE];
295   int i;
296   // boot blocks
297   memset( buffer, 0xFF, sizeof( buffer));
298   for (i=0;i<cfs->block_count_boot;i++)
299   {
300      if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_BOOT, i)) return FALSE;
301   }
302   // file blocks
303   memset( buffer, 0xFF, sizeof( buffer));
304   buffer[0] &= ~0x80;
305   for (i=0;i<cfs->block_count_file;i++)
306   {
307      if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_FILE, i)) return FALSE;
308   }
309   // ok
310   return TRUE;
311}
312
313static UINT16 cfs_calc_free_blocks( cybiko_file_system *cfs)
314{
315   UINT8 buffer[MAX_PAGE_SIZE];
316   int i;
317   UINT16 blocks = 0;
318   for (i=0;i<cfs->block_count_file;i++)
319   {
320      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return 0;
321      if (!BLOCK_USED(buffer)) blocks++;
322   }
323   return blocks;
324}
325
326static UINT32 cfs_calc_free_space( cybiko_file_system *cfs, UINT16 blocks)
327{
328   UINT32 free_space;
329   free_space = blocks * (cfs->page_size - 0x10);
330   if (free_space > 0) free_space -= FILE_HEADER_SIZE;
331   return free_space;
332}
333
334static int flash_size_to_flash_type( size_t size)
335{
336   switch (size)
337   {
338      case 0x084000 : return FLASH_TYPE_AT45DB041;
339      case 0x108000 : return FLASH_TYPE_AT45DB081;
340      case 0x210000 : return FLASH_TYPE_AT45DB161;
341      default       : return FLASH_TYPE_INVALID;
342   }
343}
344
345static int flash_option_to_flash_type( int option)
346{
347   switch (option)
348   {
349      case 0  : return FLASH_TYPE_AT45DB041;
350      case 1  : return FLASH_TYPE_AT45DB081;
351      case 2  : return FLASH_TYPE_AT45DB161;
352      default : return FLASH_TYPE_INVALID;
353   }
354}
355
356static imgtoolerr_t cybiko_image_open( imgtool_image *image, imgtool_stream *stream)
357{
358   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
359   int flash_type;
360   // init
361   flash_type = flash_size_to_flash_type( stream_size( stream));
362   if (!cfs_init( cfs, stream, flash_type)) return IMGTOOLERR_CORRUPTIMAGE;
363   // verify
364   if (!cfs_verify( cfs)) return IMGTOOLERR_CORRUPTIMAGE;
365   // ok
366   return IMGTOOLERR_SUCCESS;
367}
368
369static void cybiko_image_close( imgtool_image *image)
370{
371   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
372   stream_close( cfs->stream);
373}
374
375static imgtoolerr_t cybiko_image_create( imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
376{
377   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
378   int flash_type;
379   // init
380   flash_type = flash_option_to_flash_type( option_resolution_lookup_int( opts, 'F'));
381   if (!cfs_init( cfs, stream, flash_type)) return IMGTOOLERR_CORRUPTIMAGE;
382   // format
383   if (!cfs_format( cfs)) return IMGTOOLERR_CORRUPTIMAGE;
384   // ok
385   return IMGTOOLERR_SUCCESS;
386}
387
388static imgtoolerr_t cybiko_image_begin_enum( imgtool_directory *enumeration, const char *path)
389{
390   cybiko_iter *iter = (cybiko_iter*)imgtool_directory_extrabytes( enumeration);
391   iter->block = 0;
392   return IMGTOOLERR_SUCCESS;
393}
394
395static imgtoolerr_t cybiko_image_next_enum( imgtool_directory *enumeration, imgtool_dirent *ent)
396{
397   imgtool_image *image = imgtool_directory_image( enumeration);
398   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
399   cybiko_iter *iter = (cybiko_iter*)imgtool_directory_extrabytes( enumeration);
400   UINT8 buffer[MAX_PAGE_SIZE];
401   UINT16 file_id = INVALID_FILE_ID;
402   cfs_file file;
403   // find next file
404   while (iter->block < cfs->block_count_file)
405   {
406      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, iter->block++)) return IMGTOOLERR_READERROR;
407      if (BLOCK_USED(buffer) && (BLOCK_PART_ID(buffer) == 0))
408      {
409         file_id = BLOCK_FILE_ID(buffer);
410         break;
411      }
412   }
413   // get file information
414   if ((file_id != INVALID_FILE_ID) && cfs_file_info( cfs, file_id, &file))
415   {
416      strcpy( ent->filename, file.name);
417      ent->filesize = file.size;
418      ent->lastmodified_time = time_crack( file.date);
419      ent->filesize = file.size;
420   }
421   else
422   {
423      ent->eof = 1;
424   }
425   // ok
426   return IMGTOOLERR_SUCCESS;
427}
428
429static void cybiko_image_close_enum( imgtool_directory *enumeration)
430{
431   // nothing
432}
433
434static imgtoolerr_t cybiko_image_free_space( imgtool_partition *partition, UINT64 *size)
435{
436   imgtool_image *image = imgtool_partition_image( partition);
437   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
438   if (size) *size = cfs_calc_free_space( cfs, cfs_calc_free_blocks( cfs));
439   return IMGTOOLERR_SUCCESS;
440}
441
442static imgtoolerr_t cybiko_image_read_file( imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
443{
444   imgtool_image *image = imgtool_partition_image( partition);
445   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
446   UINT8 buffer[MAX_PAGE_SIZE];
447   UINT16 file_id, part_id = 0, old_part_id;
448   int i;
449   // find file
450   if (!cfs_file_find( cfs, filename, &file_id)) return IMGTOOLERR_FILENOTFOUND;
451   // read file
452   do
453   {
454      old_part_id = part_id;
455      for (i=0;i<cfs->block_count_file;i++)
456      {
457         if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return IMGTOOLERR_READERROR;
458         if (BLOCK_USED(buffer) && (BLOCK_FILE_ID(buffer) == file_id) && (BLOCK_PART_ID(buffer) == part_id))
459         {
460            stream_write( destf, buffer + 6 + ((part_id == 0) ? FILE_HEADER_SIZE : 0), buffer[1]);
461            part_id++;
462         }
463      }
464   } while (old_part_id != part_id);
465   // ok
466   return IMGTOOLERR_SUCCESS;
467}
468
469static imgtoolerr_t cybiko_image_write_file( imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
470{
471   imgtool_image *image = imgtool_partition_image( partition);
472   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
473   UINT8 buffer[MAX_PAGE_SIZE];
474   UINT16 file_id, part_id = 0, free_blocks;
475   UINT64 bytes_left;
476   cfs_file file;
477   int i;
478   // find file
479   if (!cfs_file_find( cfs, filename, &file_id)) file_id = INVALID_FILE_ID;
480   // check free space
481   free_blocks = cfs_calc_free_blocks( cfs);
482   if (file_id != INVALID_FILE_ID)
483   {
484      if (!cfs_file_info( cfs, file_id, &file)) return IMGTOOLERR_UNEXPECTED;
485      free_blocks += file.blocks;
486   }
487   if (cfs_calc_free_space( cfs, free_blocks) < stream_size( sourcef)) return IMGTOOLERR_NOSPACE;
488   // delete file
489   if (file_id != INVALID_FILE_ID)
490   {
491      if (!cfs_file_delete( cfs, file_id)) return IMGTOOLERR_UNEXPECTED;
492   }
493   // create/write destination file
494   bytes_left = stream_size( sourcef);
495   i = 0;
496   while ((bytes_left > 0) && (i < cfs->block_count_file))
497   {
498      if (!cfs_block_read( cfs, buffer, BLOCK_TYPE_FILE, i)) return IMGTOOLERR_READERROR;
499      if (!BLOCK_USED(buffer))
500      {
501         if (part_id == 0) file_id = i;
502         memset( buffer, 0xFF, cfs->page_size - 0x10);
503         buffer[0] = 0x80;
504         buffer[1] = cfs->page_size - 0x10 - ((part_id == 0) ? FILE_HEADER_SIZE : 0);
505         if (bytes_left < buffer[1]) buffer[1] = bytes_left;
506         buffer_write_16_be( buffer + 2, file_id);
507         buffer_write_16_be( buffer + 4, part_id);
508         if (part_id == 0)
509         {
510            buffer[6] = 0;
511            strcpy( BLOCK_FILENAME(buffer), filename);
512            buffer_write_32_be( buffer + 6 + FILE_HEADER_SIZE - 4, time_setup( time( NULL)));
513            stream_read( sourcef, buffer + 6 + FILE_HEADER_SIZE, buffer[1]);
514         }
515         else
516         {
517            stream_read( sourcef, buffer + 6, buffer[1]);
518         }
519         if (!cfs_block_write( cfs, buffer, BLOCK_TYPE_FILE, i)) return IMGTOOLERR_WRITEERROR;
520         bytes_left -= buffer[1];
521         part_id++;
522      }
523      i++;
524   }
525   // ok
526   return IMGTOOLERR_SUCCESS;
527}
528
529static imgtoolerr_t cybiko_image_delete_file( imgtool_partition *partition, const char *filename)
530{
531   imgtool_image *image = imgtool_partition_image( partition);
532   cybiko_file_system *cfs = (cybiko_file_system*)imgtool_image_extra_bytes( image);
533   UINT16 file_id;
534   // find file
535   if (!cfs_file_find( cfs, filename, &file_id)) return IMGTOOLERR_FILENOTFOUND;
536   // delete file
537   if (!cfs_file_delete( cfs, file_id)) return IMGTOOLERR_UNEXPECTED;
538   // ok
539   return IMGTOOLERR_SUCCESS;
540}
541
542OPTION_GUIDE_START( cybiko_image_createimage_optguide )
543   OPTION_ENUM_START( 'F', "flash", "Flash Type" )
544      OPTION_ENUM( 0, "AT45DB041", "AT45DB041 (528 KByte)" )
545      OPTION_ENUM( 1, "AT45DB081", "AT45DB081 (1056 KByte)" )
546      OPTION_ENUM( 2, "AT45DB161", "AT45DB161 (2112 KByte)" )
547   OPTION_ENUM_END
548OPTION_GUIDE_END
549
550//OPTION_GUIDE_START( cybiko_image_writefile_optguide )
551//   OPTION_INT( 'B', "boot", "Boot Flag" )
552//OPTION_GUIDE_END
553
554void cybiko_get_info( const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
555{
556   switch (state)
557   {
558      // --- the following bits of info are returned as 64-bit signed integers ---
559      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES          : info->i = sizeof( cybiko_file_system); break;
560      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES      : info->i = sizeof( cybiko_iter); break;
561//      case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME     : info->i = 1; break;
562      case IMGTOOLINFO_INT_SUPPORTS_LASTMODIFIED_TIME : info->i = 1; break;
563//      case IMGTOOLINFO_INT_BLOCK_SIZE                 : info->i = 264; break;
564      // --- the following bits of info are returned as pointers to data or functions ---
565      case IMGTOOLINFO_PTR_OPEN        : info->open        = cybiko_image_open; break;
566      case IMGTOOLINFO_PTR_CREATE      : info->create      = cybiko_image_create; break;
567      case IMGTOOLINFO_PTR_CLOSE       : info->close       = cybiko_image_close; break;
568      case IMGTOOLINFO_PTR_BEGIN_ENUM  : info->begin_enum  = cybiko_image_begin_enum; break;
569      case IMGTOOLINFO_PTR_NEXT_ENUM   : info->next_enum   = cybiko_image_next_enum; break;
570      case IMGTOOLINFO_PTR_CLOSE_ENUM  : info->close_enum  = cybiko_image_close_enum; break;
571      case IMGTOOLINFO_PTR_FREE_SPACE  : info->free_space  = cybiko_image_free_space; break;
572      case IMGTOOLINFO_PTR_READ_FILE   : info->read_file   = cybiko_image_read_file; break;
573      case IMGTOOLINFO_PTR_WRITE_FILE  : info->write_file  = cybiko_image_write_file; break;
574      case IMGTOOLINFO_PTR_DELETE_FILE : info->delete_file = cybiko_image_delete_file; break;
575      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE : info->createimage_optguide = cybiko_image_createimage_optguide; break;
576//      case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE   : info->writefile_optguide   = cybiko_image_writefile_optguide; break;
577      // --- the following bits of info are returned as NULL-terminated strings ---
578      case IMGTOOLINFO_STR_NAME            : strcpy( info->s = imgtool_temp_str(), "cybiko"); break;
579      case IMGTOOLINFO_STR_DESCRIPTION     : strcpy( info->s = imgtool_temp_str(), "Cybiko File System"); break;
580      case IMGTOOLINFO_STR_FILE            : strcpy( info->s = imgtool_temp_str(), __FILE__); break;
581      case IMGTOOLINFO_STR_FILE_EXTENSIONS : strcpy( info->s = imgtool_temp_str(), "bin,nv"); break;
582      case IMGTOOLINFO_STR_EOLN            : strcpy( info->s = imgtool_temp_str(), "\r\n"); break;
583      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC : strcpy( info->s = imgtool_temp_str(), "F[0]-2"); break;
584//      case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC   : strcpy( info->s = imgtool_temp_str(), "B[0]-1"); break;
585   }
586}
src/mess/tools/imgtool/modules/pc_flop.c
r0r1340
1/****************************************************************************
2
3   pc_flop.c
4
5   PC floppies
6
7****************************************************************************/
8
9#include "imgtool.h"
10#include "formats/pc_dsk.h"
11#include "iflopimg.h"
12
13#define FAT_SECLEN            512
14
15/* imports from fat.c */
16extern void fat_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info);
17
18
19
20static imgtoolerr_t fat_image_create(imgtool_image *image, imgtool_stream *stream, option_resolution *opts)
21{
22   imgtoolerr_t err;
23   UINT32 tracks, heads, sectors;
24   UINT8 buffer[FAT_SECLEN];
25   imgtool_class imgclass = { fat_get_info };
26   imgtoolerr_t (*fat_partition_create)(imgtool_image *image, UINT64 first_block, UINT64 block_count);
27
28   tracks = option_resolution_lookup_int(opts, 'T');
29   heads = option_resolution_lookup_int(opts, 'H');
30   sectors = option_resolution_lookup_int(opts, 'S');
31
32   /* set up just enough of a boot sector to specify geometry */
33   memset(buffer, 0, sizeof(buffer));
34   place_integer_le(buffer, 24, 2, sectors);
35   place_integer_le(buffer, 26, 2, heads);
36   place_integer_le(buffer, 19, 2, (UINT16) (((UINT64) tracks * heads * sectors) >> 0));
37   place_integer_le(buffer, 32, 4, (UINT16) (((UINT64) tracks * heads * sectors) >> 16));
38   err = imgtool_image_write_block(image, 0, buffer);
39   if (err)
40      goto done;
41
42   /* load fat_partition_create */
43   fat_partition_create = (imgtoolerr_t (*)(imgtool_image *, UINT64, UINT64))
44      imgtool_get_info_fct(&imgclass, IMGTOOLINFO_PTR_CREATE_PARTITION);
45
46   /* actually create the partition */
47   err = fat_partition_create(image, 0, ((UINT64) tracks) * heads * sectors);
48   if (err)
49      goto done;
50
51done:
52   return err;
53}
54
55
56
57static imgtoolerr_t   fat_image_get_geometry(imgtool_image *image, UINT32 *tracks, UINT32 *heads, UINT32 *sectors)
58{
59   imgtoolerr_t err;
60   UINT64 total_sectors;
61   UINT8 buffer[FAT_SECLEN];
62
63   err = imgtool_image_read_block(image, 0, buffer);
64   if (err)
65      return err;
66
67   total_sectors = pick_integer_le(buffer, 19, 2)
68      | (pick_integer_le(buffer, 32, 4) << 16);
69
70   *sectors = pick_integer_le(buffer, 24, 2);
71   *heads = pick_integer_le(buffer, 26, 2);
72   *tracks = total_sectors / *heads / *sectors;
73   return IMGTOOLERR_SUCCESS;
74}
75
76
77
78static imgtoolerr_t fat_get_sector_position(imgtool_image *image, UINT32 sector_index,
79   UINT32 *track, UINT32 *head, UINT32 *sector)
80{
81   imgtoolerr_t err;
82   UINT32 tracks, heads, sectors;
83
84   if (sector_index == 0)
85   {
86      /* special case */
87      *head = 0;
88      *track = 0;
89      *sector = 1;
90   }
91   else
92   {
93      err = imgtool_image_get_geometry(image, &tracks, &heads, &sectors);
94      if (err)
95         return err;
96
97      *track = sector_index / sectors / heads;
98      *head = (sector_index / sectors) % heads;
99      *sector = 1 + (sector_index % sectors);
100   }
101   return IMGTOOLERR_SUCCESS;
102}
103
104
105
106static imgtoolerr_t fat_image_readblock(imgtool_image *image, void *buffer, UINT64 block)
107{
108   imgtoolerr_t err;
109   floperr_t ferr;
110   UINT32 track, head, sector;
111   UINT32 block_size;
112
113   err = imgtool_image_get_block_size(image, &block_size);
114   if (err)
115      return err;
116
117   err = fat_get_sector_position(image, block, &track, &head, &sector);
118   if (err)
119      return err;
120
121   ferr = floppy_read_sector(imgtool_floppy(image), head, track, sector, 0, buffer, block_size);
122   if (ferr)
123      return imgtool_floppy_error(ferr);
124   return IMGTOOLERR_SUCCESS;
125}
126
127
128
129static imgtoolerr_t fat_image_writeblock(imgtool_image *image, const void *buffer, UINT64 block)
130{
131   imgtoolerr_t err;
132   floperr_t ferr;
133   UINT32 track, head, sector;
134   UINT32 block_size;
135
136   err = imgtool_image_get_block_size(image, &block_size);
137   if (err)
138      return err;
139
140   err = fat_get_sector_position(image, block, &track, &head, &sector);
141   if (err)
142      return err;
143
144   ferr = floppy_write_sector(imgtool_floppy(image), head, track, sector, 0, buffer, block_size);
145   if (ferr)
146      return imgtool_floppy_error(ferr);
147   return IMGTOOLERR_SUCCESS;
148}
149
150
151
152void pc_floppy_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
153{
154   switch(state)
155   {
156      /* --- the following bits of info are returned as 64-bit signed integers --- */
157      case IMGTOOLINFO_INT_BLOCK_SIZE:               info->i = FAT_SECLEN; break;
158
159      /* --- the following bits of info are returned as NULL-terminated strings --- */
160      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "fat"); break;
161      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "FAT format"); break;
162
163      /* --- the following bits of info are returned as pointers to data or functions --- */
164      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
165      case IMGTOOLINFO_PTR_FLOPPY_CREATE:               info->create = fat_image_create; break;
166      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_pc; break;
167      case IMGTOOLINFO_PTR_READ_BLOCK:               info->read_block = fat_image_readblock; break;
168      case IMGTOOLINFO_PTR_WRITE_BLOCK:               info->write_block = fat_image_writeblock; break;
169      case IMGTOOLINFO_PTR_GET_GEOMETRY:               info->get_geometry = fat_image_get_geometry; break;
170
171      default: fat_get_info(imgclass, state, info); break;
172   }
173}
src/mess/tools/imgtool/modules/svi_cas.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "formats/svi_cas.h"
6#include "imgtoolx.h"
7#include "utils.h"
8
9/*
10   SVI module
11
12   SVI style .cas for the svi-318 and svi-328. Converts them to .wav files.
13   Uses the mess/formats/svi_cas.[ch] files, for the actual conversion.
14*/
15
16typedef struct {
17   imgtool_image         base;
18   char         *file_name;
19   imgtool_stream          *file_handle;
20   int          size;
21   unsigned char   *data;
22   INT16         *wavdata;
23   int          count;
24   } CAS_IMAGE;
25
26typedef struct
27   {
28   imgtool_directory    base;
29   CAS_IMAGE   *image;
30   int         index;
31   } CAS_ITERATOR;
32
33static int svi_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
34static void svi_cas_image_exit(imgtool_image *img);
35//static void svi_cas_image_info(imgtool_image *img, char *string, const int len);
36static int svi_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
37static int svi_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
38static void svi_cas_image_closeenum(imgtool_directory *enumeration);
39static int svi_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
40
41IMAGEMODULE(
42   svi_cas,
43   "SVI-318/SVI-328 .cas file",            /* human readable name */
44   "cas",                        /* file extension */
45   NULL,                        /* crcfile */
46   NULL,                        /* crc system name */
47   NULL,                        /* eoln */
48   0,
49   svi_cas_image_init,            /* init function */
50   svi_cas_image_exit,            /* exit function */
51   NULL,                        /* info function */
52   svi_cas_image_beginenum,         /* begin enumeration */
53   svi_cas_image_nextenum,         /* enumerate next */
54   svi_cas_image_closeenum,         /* close enumeration */
55   NULL,                        /* free space on image */
56   svi_cas_image_readfile,         /* read file */
57   NULL,/* write file */
58   NULL,/* delete file */
59   NULL,/* create image */
60   NULL,                        /* read sector */
61   NULL,                        /* write sector */
62   NULL,               /* file options */
63   NULL               /* create options */
64)
65
66static int svi_cas_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
67   {
68   CAS_IMAGE *image;
69   int len, i;
70   char *pbase;
71   char default_name[] = "svitape";
72
73   image = (CAS_IMAGE*)malloc (sizeof (CAS_IMAGE) );
74   if (!image) return IMGTOOLERR_OUTOFMEMORY;
75
76   *outimg = (imgtool_image*)image;
77
78   memset(image, 0, sizeof(CAS_IMAGE));
79   image->base.module = mod;
80   image->size=stream_size(f);
81   image->file_handle=f;
82
83    if (image->size < 17)
84      {
85      free (image);
86      return IMGTOOLERR_CORRUPTIMAGE;
87      }
88
89   image->data = (unsigned char *) malloc(image->size);
90   if ( (!image->data)
91       ||(stream_read(f, image->data, image->size)!=image->size) )
92      {
93      free(image);
94      *outimg=NULL;
95      return IMGTOOLERR_OUTOFMEMORY;
96      }
97
98     i = svi_cas_to_wav (image->data, image->size, &image->wavdata, &image->count);
99     if (i)
100      {
101      free(image->data);
102      free(image);
103      *outimg=NULL;
104      return (i == 2) ? IMGTOOLERR_OUTOFMEMORY : IMGTOOLERR_CORRUPTIMAGE;
105      }
106
107    pbase = NULL;
108    if (pbase) len = strlen (pbase);
109    else len = strlen (default_name);
110
111    image->file_name = malloc (len + 5);
112   if (!image->file_name)
113      {
114      free(image->data);
115      free(image);
116      *outimg=NULL;
117      return IMGTOOLERR_CORRUPTIMAGE;
118      }
119
120    if (!pbase)
121      strcpy (image->file_name, default_name);
122    else
123      {
124      strcpy (image->file_name, pbase);
125        if (len > 4)
126         if (!strncmpi (".cas", image->file_name + len - 4, 4) ) len -= 4;
127
128      strcpy (image->file_name + len, ".wav");
129      }
130
131   return 0;
132   }
133
134static void svi_cas_image_exit(imgtool_image *img)
135   {
136   CAS_IMAGE *image=(CAS_IMAGE*)img;
137   stream_close(image->file_handle);
138   free(image->file_name);
139   free(image->data);
140   free(image->wavdata);
141   free(image);
142   }
143
144static int svi_cas_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
145   {
146   CAS_IMAGE *image=(CAS_IMAGE*)img;
147   CAS_ITERATOR *iter;
148
149   iter=*(CAS_ITERATOR**)outenum = (CAS_ITERATOR*) malloc(sizeof(CAS_ITERATOR));
150   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
151
152   iter->base.module = img->module;
153
154   iter->image=image;
155   iter->index = 0;
156   return 0;
157   }
158
159static int svi_cas_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
160   {
161   CAS_ITERATOR *iter=(CAS_ITERATOR*)enumeration;
162
163   ent->eof=iter->index;
164   if (!ent->eof)
165      {
166      strcpy (ent->fname, iter->image->file_name);
167      ent->corrupt=0;
168      ent->filesize = iter->image->count * 2 + 0x2c;
169      iter->index++;
170      }
171
172   return 0;
173   }
174
175static void svi_cas_image_closeenum(imgtool_directory *enumeration)
176   {
177   free(enumeration);
178   }
179
180static int svi_cas_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
181   {
182   CAS_IMAGE *image=(CAS_IMAGE*)img;
183   INT16 *wavdata;
184   UINT16   temp16;
185   UINT32   temp32;
186   int wavlen, offset;
187
188   if (mame_stricmp (fname, image->file_name) )
189      return IMGTOOLERR_MODULENOTFOUND;
190
191   wavdata = image->wavdata;
192   wavlen = image->count;
193    /* write the core header for a WAVE file */
194   offset = stream_write(destf, "RIFF", 4);
195    if( offset < 4 )
196      return IMGTOOLERR_WRITEERROR;
197
198   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2 + 0x24);
199   offset += stream_write(destf, &temp32, 4);
200    if( offset < 8 )
201      return IMGTOOLERR_WRITEERROR;
202
203   /* read the RIFF file type and make sure it's a WAVE file */
204   offset += stream_write(destf, "WAVEfmt ", 8);
205   if( offset < 16 )
206      return IMGTOOLERR_WRITEERROR;
207
208    /* size of the following 'fmt ' fields */
209    offset += stream_write(destf, "\x10\x00\x00\x00", 4);
210   if( offset < 20 )
211      return IMGTOOLERR_WRITEERROR;
212
213   /* format: PCM */
214   temp16 = LITTLE_ENDIANIZE_INT16 (1);
215   offset += stream_write(destf, &temp16, 2);
216   if( offset < 22 )
217      return IMGTOOLERR_WRITEERROR;
218
219   /* channels: 1 (mono) */
220   temp16 = LITTLE_ENDIANIZE_INT16 (1);
221   offset += stream_write(destf, &temp16, 2);
222   if( offset < 24 )
223      return IMGTOOLERR_WRITEERROR;
224
225   /* sample rate */
226   temp32 = LITTLE_ENDIANIZE_INT32(22050);
227   offset += stream_write(destf, &temp32, 4);
228   if( offset < 24 )
229      return IMGTOOLERR_WRITEERROR;
230
231   /* byte rate */
232   temp32 = LITTLE_ENDIANIZE_INT32(22050 * 2);
233   offset += stream_write(destf, &temp32, 4);
234   if( offset < 28 )
235      return IMGTOOLERR_WRITEERROR;
236
237   /* block align (size of one `sample') */
238   temp16 = LITTLE_ENDIANIZE_INT16 (2);
239   offset += stream_write(destf, &temp16, 2);
240   if( offset < 30 )
241      return IMGTOOLERR_WRITEERROR;
242
243   /* block align */
244   temp16 = LITTLE_ENDIANIZE_INT16 (16);
245   offset += stream_write(destf, &temp16, 2);
246   if( offset < 32 )
247      return IMGTOOLERR_WRITEERROR;
248
249   /* 'data' tag */
250   offset += stream_write(destf, "data", 4);
251   if( offset < 36 )
252      return IMGTOOLERR_WRITEERROR;
253
254   /* data size */
255   temp32 = LITTLE_ENDIANIZE_INT32(image->count * 2);
256   offset += stream_write(destf, &temp32, 4);
257   if( offset < 40 )
258      return IMGTOOLERR_WRITEERROR;
259
260   if (stream_write(destf, wavdata, (image->count*2))!=(image->count*2))
261      return IMGTOOLERR_WRITEERROR;
262
263   return 0;
264   }
265
src/mess/tools/imgtool/modules/thomson.c
r0r1340
1/****************************************************************************
2
3  Copyright (C) Antoine Mine' 2006
4
5  Thomson 8-bit micro-computers.
6
7  Handles SAP, QD and FD floppy formats with a BASIC-DOS filesystem
8  (most floppies except some games and demo).
9
10*****************************************************************************/
11
12/* TODO:
13   - improve two-sided floppy support
14   - check & correct BASIC read filter
15   - implement BASIC write filter
16   - handle accented letters
17 */
18
19
20/* Thomson floppy geometry are:
21   - 5"1/4 single density: 40 tracks, 16 sectors/track, 128 bytes/sector
22   - 5"1/4 double density: 40 tracks, 16 sectors/track, 256 bytes/sector
23   - 3"1/2 double density: 80 tracks, 16 sectors/track, 256 bytes/sector
24   - 2"8: 25 logical tracks, 16 logical sectors/track, 128 bytes/sector
25
26   Notes:
27
28   - 2"8 QDD actually contain a single spiraling track, with 400 128-byte
29   sectors; however, the filesystem considers it has 25 virtual tracks of
30   16 sectors => we do the same in imgtool (but thomflop.c uses a 400-sector
31   addressing to emulate the device hardware)
32
33   - tracks always have 16 sectors, this is requred by the filesystem
34
35   - two-sided floppies are handled as two one-sided floppies in two
36   logical floppy drives on the original Thomsons; each has its own
37   independent FAT and directory.
38   In imgtool, we handle two-sided images as two partitions.
39   For now, only 3"1/2 .fd and QDD .qd files can be two-sided.
40
41   - it seems possible to create 3"1/2 single density floppies on the TO9,
42   I am not sure this is standard, and we do not support it...
43
44*/
45
46
47/* Microsoft BASIC Filesystem.
48
49   The floppy is divided into blocks, with always two blocks / track.
50   Also, in double density, only the first 255 bytes of each 256-byte
51   sector is used. Thus, blocks are 1024 bytes in single density, and
52   2040 bytes in double density.
53   Depending on the number of tracks, there can be 50, 80 or 160 blocks.
54
55   Filesystem data always occupy track 20, whatever the floppy geometry.
56   
57   * sector 1:
58     - bytes 0-7: floppy name
59     - remaining bytes: undocumented, seem unused
60
61   * sector 2: FAT, 1 byte info per block
62     - byte 0: always 0
63     - byte 1: block 0
64        ...
65     - byte i: block i-1
66        ...
67     - byte 160: block 159
68     - remaining bytes: undocumented, seem unused
69
70     The byte has the following meaning:
71     - ff: block is free
72     - fb: block is reserved
73     - 00-bf: block allocated, points to then next file block
74     - c1-c8: last block in file, (value & 15) is the number of sectors
75              actually allocated to the file
76
77     Note: in single density, we can reference only 127 blocks. This is not
78     a problem because single density floppies can only have 50 or 80 blocks,
79     never 160.
80     
81   * sector 3-16: directory
82
83     no subdirectories
84
85     each file entry occupies 32 bytes:
86     - bytes 00-07: filename, padded with whitespaces
87     - bytes 08-0A: file extension, padedd with whitespaces
88     - byte  0B:    file type
89                    . 0 = BASIC, ASCII or binary program (B)
90             . 1 = BASIC or ASCII data (D)
91          . 2 = machine code (M)
92          . 3 = ASCII assembler file (A)
93     - byte  0C:    format flag
94           . 00 = binary (tokenized)
95                    . ff = ASCII
96     - byte  0D:    first block
97     - bytes 0E-0F: bytes used in the last sector
98     - bytes 10-17: comment
99     - byte 18:     day (of month)
100     - byte 19:     month
101     - byte 1A:     year (two last digits)
102     - bytes 1B-1f: unknown
103
104     Note that byte 0 has a special significance:
105     - 00:    free directory entry
106     - 20-7F: actual directory entry, value is the first character ini filename
107     - ff:    end of directory
108
109     There can be 56 files in single density, 112 in double density.
110 */
111
112#include "imgtool.h"
113#include "iflopimg.h"
114#include "formats/basicdsk.h"
115
116#include <time.h>
117
118
119#define MAXSIZE 80*16*256*2 /* room for two faces, double-density, 80 tracks */
120
121typedef struct {
122
123  imgtool_stream *stream;
124
125  UINT16 sector_size;   /* 128 or 256 */
126  UINT16 sectuse_size;  /* bytes used in sector: 128 or 255 */
127  UINT8  tracks;        /* 25, 40, or 80 */
128  UINT8  heads;         /* 1 or 2 */
129  UINT8  data[MAXSIZE]; /* image data */
130
131  int    modified;      /* data need to be copied back to image file */
132
133} thom_floppy;
134
135
136typedef enum {
137
138  THOM_DIRENT_END,
139  THOM_DIRENT_FREE,
140  THOM_DIRENT_FILE,
141  THOM_DIRENT_INVALID,
142
143} thom_dirent_type;
144
145
146typedef struct {
147
148  thom_dirent_type type;
149  int    index;
150
151  char   name[9];
152  char   ext[4];
153  char   comment[9];
154  UINT8  ftype;
155  UINT8  format;
156  UINT8  firstblock;
157  UINT16 lastsectsize;
158  UINT8  day;
159  UINT8  month;
160  UINT8  year;
161
162} thom_dirent;
163
164
165static void thom_basic_get_info(const imgtool_class *clas, UINT32 param,
166            union imgtoolinfo *info);
167
168static UINT8* thom_get_sector(thom_floppy* f, unsigned head,
169               unsigned track, unsigned sector);
170
171
172/*********************** .fd / .qd format ************************/
173
174/* .fd and .qd formats are very simple: the sectors are simply put one after
175   another, starting at sector 1 of track 0 to sector 16 track 0, then
176   starting again at sector 1 of track 1, and so on.
177   There is no image or sector header, and no gap between sectors.
178   The number of tracks and sector size are determined by the extension
179   (.fd have 40 or 80 tracks, .qd have 25 tracks) and the file size.
180*/
181
182static imgtoolerr_t thom_open_fd_qd(imgtool_image *img, imgtool_stream *stream)
183{
184  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
185  int size = stream_size( stream );
186 
187  f->stream = stream;
188  f->modified = 0;
189
190  /* guess format */
191  switch ( size ) {
192
193  case 81920:
194    f->tracks = 40;
195    f->sector_size = 128;
196    f->sectuse_size = 128;
197    f->heads = 1;
198    break;
199
200  case 163840:
201    f->tracks = 40;
202    f->sector_size = 256;
203    f->sectuse_size = 255;
204    f->heads = 1;
205    /* could also be: sector_size=128, heads=2 */
206    /* maight even be: tracks=80, sector_size=128 */
207    break;
208
209  case 327680:
210    f->tracks = 80;
211    f->sector_size = 256;
212    f->sectuse_size = 255;
213    f->heads = 1;
214    /* could also be: tracks=40, heads=2 */
215    break;
216
217  case 655360:
218    f->tracks = 80;
219    f->sector_size = 256;
220    f->sectuse_size = 255;
221    f->heads = 2;
222    break;
223
224  case 51200:
225    f->tracks = 25;
226    f->sector_size = 128;
227    f->sectuse_size = 128;
228    f->heads = 1;
229    break;
230
231  case 62400:
232    f->tracks = 25;
233    f->sector_size = 128;
234    f->sectuse_size = 128;
235    f->heads = 2;
236    break;
237
238  default:
239    return IMGTOOLERR_CORRUPTIMAGE;
240  }
241 
242  assert( size == f->heads * f->tracks * 16 * f->sector_size );
243
244  stream_seek( stream, 0, SEEK_SET );
245  if ( stream_read( stream, f->data, size ) < size )
246    return IMGTOOLERR_READERROR;
247
248  return IMGTOOLERR_SUCCESS;
249}
250
251static void thom_close_fd_qd(imgtool_image *img)
252{
253  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
254
255  /* save image */
256  if ( f->modified ) {
257    int size = f->heads * f->tracks * 16 * f->sector_size;
258    stream_seek( f->stream, 0, SEEK_SET );
259    if ( stream_write( f->stream, f->data, size ) < size )
260      logerror( "thom_diskimage_close_fd_qd: write error\n" );
261  }
262
263  stream_close( f->stream );
264}
265
266
267/*********************** .sap format ************************/
268
269/* SAP format, Copyright 1998 by Alexandre Pukall
270
271   image is composed of:
272   - byte 0:        version (0 or 1)
273   - bytes 1..65:   signature
274   - bytes 66..end: sectors
275 
276   each sector is composed of
277   - a 4-byte header:
278     . byte 0:     format
279                      0 3"1/2 double density
280                      1 5"1/4 low density
281     . byte 1:     protection (?)
282     . byte 2:     track index, in 0..79
283     . byte 3:     sector index, in 1..16
284   - sector data, XOR 0xB3
285   - 2-byte CRC of header + data, high byte first
286
287   there is no provision for two-sided images in sap
288 */
289
290static const int sap_magic_num = 0xB3; /* simple XOR crypt */
291
292static const char sap_header[]=
293  "\001SYSTEME D'ARCHIVAGE PUKALL S.A.P. "
294  "(c) Alexandre PUKALL Avril 1998";
295
296static const UINT16 sap_crc[] = {
297  0x0000, 0x1081, 0x2102, 0x3183,   0x4204, 0x5285, 0x6306, 0x7387,
298  0x8408, 0x9489, 0xa50a, 0xb58b,   0xc60c, 0xd68d, 0xe70e, 0xf78f,
299};
300
301static UINT16 thom_sap_crc( UINT8* data, int size )
302{
303  int i;
304  UINT16 crc = 0xffff, crc2;
305  for ( i = 0; i < size; i++ ) {
306    crc2 = ( crc >> 4 ) ^ sap_crc[ ( crc ^ data[i] ) & 15 ];
307    crc = ( crc2 >> 4 ) ^ sap_crc[ ( crc2 ^ (data[i] >> 4) ) & 15 ];
308  }
309  return crc;
310}
311
312static imgtoolerr_t thom_open_sap(imgtool_image *img, imgtool_stream *stream)
313{
314  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
315  UINT8 buf[262];
316 
317  f->stream = stream;
318  f->modified = 0;
319
320 /* check image header */
321  stream_seek( stream, 0, SEEK_SET );
322  stream_read( stream, buf, 66 );
323  if ( memcmp( buf+1, sap_header+1, 65 ) ) return IMGTOOLERR_CORRUPTIMAGE;
324
325  /* guess format */
326  stream_read( stream, buf, 1 );
327  switch ( buf[0] ) {
328  case 1:
329  case 3:
330    f->heads = 1;
331    f->tracks = 40;
332    f->sector_size = 128;
333    f->sectuse_size = 128;
334    break;
335  case 0:
336  case 2:
337  case 4:
338    f->heads = 1;
339    f->tracks = 80;
340    f->sector_size = 256;
341    f->sectuse_size = 255;
342    break;
343  default: return IMGTOOLERR_CORRUPTIMAGE;
344  }
345 
346 stream_seek( stream, 66, SEEK_SET );
347  while ( 1) {
348    int i, sector, track;
349    UINT16 crc;
350
351    /* load sector */
352    if ( stream_read( stream, buf, 6 + f->sector_size ) < 6 + f->sector_size )
353      break;
354
355    /* parse sector header */
356    track = buf[2];
357    sector = buf[3];
358    if ( sector < 1 || sector > 16 || track >= f->tracks )
359      return IMGTOOLERR_CORRUPTIMAGE;
360
361    /* decrypt */
362    for ( i = 0; i < f->sector_size; i++ ) buf[ i + 4 ] ^= sap_magic_num;
363    memcpy( thom_get_sector( f, 0, track, sector ), buf + 4, f->sector_size );
364
365    /* check CRC */
366    crc = thom_sap_crc( buf, f->sector_size + 4 );
367    if ( ( (crc >> 8)   != buf[ f->sector_size + 4 ] ) ||
368         ( (crc & 0xff) != buf[ f->sector_size + 5 ] ) )
369      return IMGTOOLERR_CORRUPTIMAGE;
370  }
371
372  return IMGTOOLERR_SUCCESS;
373}
374
375static void thom_close_sap(imgtool_image *img)
376{
377  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
378
379  if ( f->modified ) {
380    int i, sector, track;
381    UINT8 buf[262];
382    UINT16 crc;
383
384    /* rewind */
385    stream_seek( f->stream, 0, SEEK_SET );
386
387    /* image header */
388    if ( stream_write( f->stream, sap_header, 66 ) < 66 ) {
389      logerror( "thom_diskimage_close_sap: write error\n" );
390      return;
391    }
392   
393    for ( track = 0; track < f->tracks; track++ )
394      for ( sector = 1; sector <= 16; sector++ ) {
395
396   /* sector header & data */
397   buf[0] = ( f->tracks == 80 ) ? 2 : 1;
398   buf[1] = 0;
399   buf[2] = track;
400   buf[3] = sector;
401   memcpy( buf + 4,
402      thom_get_sector( f, 0, track, sector), f->sector_size );
403
404   /* compute crc */
405   crc = thom_sap_crc( buf, f->sector_size + 4 );
406   buf[ f->sector_size + 4 ] = crc >> 8;
407   buf[ f->sector_size + 5 ] = crc & 0xff;
408
409   /* crypt */
410   for ( i = 0; i < f->sector_size; i++ ) buf[ i + 4 ] ^= sap_magic_num;
411
412   /* save */
413   if ( stream_write( f->stream, buf, f->sector_size + 6 ) <
414        f->sector_size + 6 ) {
415     logerror( "thom_diskimage_close_sap: write error\n" );
416     return;
417   }
418      }
419  }
420 
421  stream_close( f->stream );
422}
423
424
425/*********************** low-level functions *********************/
426
427static UINT8* thom_get_sector(thom_floppy* f, unsigned head,
428               unsigned track, unsigned sector)
429{
430  assert( head < f->heads);
431  assert( track < f->tracks );
432  assert( sector > 0 && sector <= 16 );
433  return & f->data[ ( (head * f->tracks + track) * 16 + (sector-1) ) *
434          f->sector_size ];
435}
436
437static int thom_nb_blocks(thom_floppy* f)
438{
439  int n1 = f->tracks * 2;      /* 2 blocks per track */
440  int n2 = f->sector_size - 1; /* FAT entries */
441  return (n1 < n2) ? n1 : n2;
442}
443
444static int thom_max_dirent(thom_floppy* f)
445{
446  return 14 * f->sector_size / 32;
447}
448
449/* remove trailing spaces */
450static void thom_stringify(char* str)
451{
452  char* s = str + strlen(str) - 1;
453  while ( s >= str && *s == ' ' ) { *s = 0; s--; }
454  for ( s = str; *s; s++ )
455    if ( (UINT8)*s == 0xff ) *s = 0;
456    else if ( *s < ' ' || *s >= 127 ) *s = '?';
457}
458
459/* pad with spaces until the length is nb */
460static void thom_unstringity(char* str, int nb)
461{
462  char* s = str;
463  while ( s < str + nb && *s ) s++;
464  while ( s < str + nb ) { *s = ' '; s++; }
465}
466
467/* get filename and extension & truncate them to 8 + 3 */
468static void thom_conv_filename(const char* s, char name[9], char ext[4])
469{
470  int i;
471  memset( name, 0, 9 );
472  memset( ext, 0, 4 );
473  for ( i = 0; i < 8 && *s && *s != '.'; i++, s++ ) name[i] = *s;
474  while ( *s && *s != '.' ) s++;
475  if ( *s == '.' ) {
476    s++;
477    for ( i = 0; i < 3 && *s; i++, s++ ) ext[i] = *s;
478  }
479}
480
481static time_t thom_crack_time(thom_dirent* d)
482{
483  struct tm t;
484  time_t now;
485
486  /* check */
487  if ( d->day < 1 || d->day > 31 || d->month < 1 || d->month > 12 ) return 0;
488
489  /* converts */
490  time( &now );
491  t = *localtime( &now );
492  t.tm_sec = 0;
493  t.tm_min = 0;
494  t.tm_hour = 0;
495  t.tm_mday = d->day;
496  t.tm_mon = d->month - 1;
497  t.tm_year = (d->year < 65 ) ? d->year + 100 : d->year;
498  return mktime(&t);
499}
500
501static void thom_make_time(thom_dirent* d, time_t time)
502{
503  if ( ! time ) {
504    d->day = d->month = d->year = 0;
505  }
506  else {
507    struct tm t = *localtime( &time );
508    d->day = t.tm_mday;
509    d->month = t.tm_mon + 1;
510    d->year = t.tm_year % 100;
511  }
512}
513
514static void thom_make_time_now(thom_dirent* d)
515{
516  time_t now;
517  time( &now );
518  thom_make_time( d, now );
519}
520
521static void thom_get_dirent(thom_floppy* f, unsigned head,
522             unsigned n, thom_dirent* d)
523{
524  UINT8* base = thom_get_sector( f, head, 20, 3 ) + n * 32;
525  memset( d, 0, sizeof(*d) );
526  d->index = n;
527  if ( n >= thom_max_dirent( f ) )
528    d->type = THOM_DIRENT_END;
529  else if ( *base == 0xff )
530    d->type = THOM_DIRENT_END;
531  else if ( *base == 0 )
532    d->type = THOM_DIRENT_FREE;
533  else {
534    int i;
535    /* fill regular entry */
536    d->type = THOM_DIRENT_FILE;
537    memcpy( d->name, base, 8 );
538    memcpy( d->ext, base + 8, 3 );
539    memcpy( d->comment, base + 16, 8 );
540    thom_stringify( d->name );
541    thom_stringify( d->ext );
542    thom_stringify( d->comment );
543    d->ftype = base[11];
544    d->format = base[12];
545    d->firstblock = base[13];
546    d->lastsectsize = ((int)base[14] << 8) + base[15];
547    d->day = base[24];
548    d->month = base[25];
549    d->year = base[26];
550    /* sanity check */
551    for ( i = 0; i < 11; i++ )
552      if ( base[i] < ' ' || base[i] > 127 ) d->type = THOM_DIRENT_INVALID;
553  }
554}
555
556static void thom_set_dirent(thom_floppy* f, unsigned head,
557             unsigned n, thom_dirent* d)
558{
559  UINT8* base = thom_get_sector( f, head, 20, 3 ) + n * 32;
560  if ( n >= thom_max_dirent( f ) ) return;
561  memset( base, 0, 32 );
562  if ( d->type == THOM_DIRENT_END ) base[ 0 ] = 0xff;
563  else if ( d->type == THOM_DIRENT_FREE ) base[ 0 ] = 0;
564  else {
565    memcpy( base, d->name, 8 );
566    memcpy( base + 8, d->ext, 3 );
567    memcpy( base + 16, d->comment, 8 );
568    thom_unstringity( (char*)base, 8 );
569    thom_unstringity( (char*)base + 8, 3 );
570    if ( base[16] ) thom_unstringity( (char*)base + 16, 8 );
571    base[11] = d->ftype;
572    base[12] = d->format;
573    base[13] = d->firstblock;
574    base[14] = d->lastsectsize >> 8;
575    base[15] = d->lastsectsize & 0xff;
576    base[24] = d->day;
577    base[25] = d->month;
578    base[26] = d->year;
579  }
580  f->modified = 1;
581}
582
583/* returns 1 if file found, 0 if not */
584static int thom_find_dirent(thom_floppy* f, unsigned head,
585             const char* name, thom_dirent* d)
586{
587  int n = 0;
588  while ( 1 ) {
589    thom_get_dirent( f, head, n, d );
590    if ( d->type == THOM_DIRENT_END ) return 0;
591    if ( d->type == THOM_DIRENT_FILE ) {
592      char buf[13];
593      sprintf( buf, "%s.%s", d->name, d->ext );
594      if ( ! strcmp( buf, name ) ) return 1;
595    }
596    n++;
597  }
598}
599
600/* returns 1 if free entry found, 0 if none available */
601static int thom_find_free_dirent(thom_floppy* f, unsigned head, thom_dirent* d)
602{
603  int n = 0;
604  while ( 1 ) {
605    thom_get_dirent( f, head, n, d );
606    if ( d->type == THOM_DIRENT_FREE ) return 1;
607    if ( d->type == THOM_DIRENT_END ) break;
608    n++;
609  }
610  if ( n + 1 >= thom_max_dirent( f ) ) return 0;
611  thom_set_dirent( f, head, n+1, d );
612  d->type = THOM_DIRENT_FREE;
613  return 1;
614}
615
616/* returns the file size in bytes, or -1 if error */
617static int thom_get_file_size(thom_floppy* f, unsigned head, thom_dirent* d)
618{
619  UINT8* fat = thom_get_sector( f, head, 20, 2 );
620  int nbblocks = thom_nb_blocks(f);
621  int block = d->firstblock;
622  int size = 0;
623  int timeout = nbblocks;
624  if ( d->type != THOM_DIRENT_FILE ) return -1;
625  if ( block >= nbblocks ) return -1;
626  block = fat[ block + 1 ];
627  while ( 1 ) {
628    if ( block < nbblocks ) {
629      /* full block */
630      size += 8 * f->sectuse_size;
631      block = fat[ block + 1 ];
632    }
633    else if ( block >= 0xc1 && block <= 0xc8 ) {
634      /* last block in file */
635      size += (block-0xc1) * f->sectuse_size;
636      size += d->lastsectsize;
637      return size;
638    }
639    else return -1;
640    timeout--;
641    if ( timeout < 0 ) return -1;
642   }
643}
644
645/* number of blocks used by file */
646static int thom_get_file_blocks(thom_floppy* f, unsigned head, thom_dirent* d)
647{
648  UINT8* fat = thom_get_sector( f, head, 20, 2 );
649  int nbblocks = thom_nb_blocks(f);
650  int block = d->firstblock;
651  int nb = 0;
652  if ( d->type != THOM_DIRENT_FILE ) return 0;
653  if ( block >= nbblocks ) return 0;
654  block = fat[ block + 1 ];
655  while ( 1 ) {
656    if ( block < nbblocks ) {
657      /* full block */
658      nb++;
659      block = fat[ block + 1 ];
660    }
661    else if ( block >= 0xc1 && block <= 0xc8 ) {
662      /* last block in file */
663      nb++;
664      return nb;
665    }
666    else return nb;
667  }
668}
669
670/* number of free blocks */
671static int thom_get_free_blocks(thom_floppy* f, unsigned head)
672{
673  UINT8* fat = thom_get_sector( f, head, 20, 2 );
674  int nbblocks = thom_nb_blocks(f);
675  int i, nb = 0;
676  for ( i = 1; i <= nbblocks; i++ )
677    if ( fat[i] == 0xff ) nb++;
678  return nb;
679}
680
681/* dump file contents into dst */
682static void thom_get_file(thom_floppy* f, unsigned head,
683           thom_dirent* d, imgtool_stream *dst)
684{
685  UINT8* fat = thom_get_sector( f, head, 20, 2 );
686  int nbblocks = thom_nb_blocks(f);
687  int block = d->firstblock;
688  if ( block >= nbblocks ) return;
689  while ( 1 ) {
690    int nextblock = fat[ block + 1 ];
691    int track = block / 2;
692    int firstsect = (block % 2) ? 9 : 1;
693    if ( nextblock < nbblocks ) {
694      /* full block */
695      int i;
696      for ( i = 0; i < 8; i++ ) {
697   UINT8* data = thom_get_sector( f, head, track, firstsect + i );
698   stream_write( dst, data, f->sectuse_size );
699      }
700      block = fat[ block + 1 ];
701    }
702    else if ( nextblock >= 0xc1 && nextblock <= 0xc8 ) {
703      /* last block in file */
704      int i;
705      UINT8* data;
706      for ( i = 0; i < nextblock - 0xc1; i++ ) {
707   data = thom_get_sector( f, head, track, firstsect + i );
708   stream_write( dst, data, f->sectuse_size );
709      }
710      data = thom_get_sector( f, head, track, firstsect + i );
711      stream_write( dst, data, d->lastsectsize );
712      return;
713    }
714    else {
715      /* invalid, assume last block */
716      UINT8* data = thom_get_sector( f, head, track, firstsect );
717      stream_write( dst, data, d->lastsectsize );
718      return;
719    }
720    block = nextblock;
721  }
722}
723
724static void thom_del_file(thom_floppy* f, unsigned head, thom_dirent* d)
725{
726  UINT8* fat = thom_get_sector( f, head, 20, 2 );
727  int nbblocks = thom_nb_blocks(f);
728  int block = d->firstblock;
729  if ( d->type != THOM_DIRENT_FILE ) return;
730  if ( block >= nbblocks ) return;
731  while ( 1 ) {
732    int nextblock = fat[ block + 1 ];
733    fat[ block ] = 0xff;
734    if ( nextblock < nbblocks ) block = fat[ block + 1 ];
735    else break;
736  }
737  d->type = THOM_DIRENT_FREE;
738  thom_set_dirent( f, head, d->index, d );
739  f->modified = 1;
740}
741
742/* create a new file or overwrite an old one, with the contents of src */
743static void thom_put_file(thom_floppy* f, unsigned head,
744           thom_dirent* d, imgtool_stream *src)
745{
746  int size = stream_size( src );
747  UINT8* fat = thom_get_sector( f, head, 20, 2 );
748  int nbblocks = thom_nb_blocks(f);
749  int block;
750
751  /* find first free block */
752  for ( block = 0; block < nbblocks && fat[ block + 1 ] != 0xff; block++ );
753  if ( block >= nbblocks ) return;
754  d->firstblock = block;
755
756  /* store file */
757  while (1) {
758    int track = block / 2;
759    int firstsect = (block % 2) ? 9 : 1;
760    int i;
761
762    /* store data, full sectors */
763    for ( i = 0; i < 8 && size > f->sectuse_size; i++ ) {
764      UINT8* dst = thom_get_sector( f, head, track, firstsect + i );
765      stream_read( src, dst, f->sectuse_size );
766      size -= f->sectuse_size;
767    }
768
769    /* store data, last sector */
770    if ( i < 8 ) {
771      UINT8* dst = thom_get_sector( f, head, track, firstsect + i );
772      stream_read( src, dst, size );
773      fat[ block + 1 ] = 0xc1 + i;
774      d->lastsectsize = size;
775      break;
776    }
777   
778    /* find next free block & update fat */
779    i = block;
780    for ( block++; block < nbblocks && fat[ block + 1 ] != 0xff; block++ );
781    if ( block >= nbblocks ) {
782      /* out of memory! */
783      fat[ i + 1 ] = 0;
784      d->lastsectsize = 0;
785      break;
786    }
787    fat[ i + 1 ] = block;
788  }
789
790  d->type = THOM_DIRENT_FILE;
791  thom_set_dirent( f, head, d->index, d );
792  f->modified = 1;
793}
794
795
796/********************** module functions ***********************/
797
798static imgtoolerr_t thom_get_sector_size(imgtool_image* img, UINT32 track,
799                UINT32 head, UINT32 sector,
800                UINT32 *sector_size)
801{
802  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
803 
804  if ( head >= f->heads || sector < 1 || sector > 16 || track >= f->tracks ) {
805    if ( sector_size ) *sector_size = 0;
806    return IMGTOOLERR_SEEKERROR;
807  }
808  if ( sector_size ) *sector_size = f->sector_size;
809  return IMGTOOLERR_SUCCESS;
810}
811
812static imgtoolerr_t thom_get_geometry(imgtool_image* img, UINT32* tracks,
813                  UINT32* heads, UINT32* sectors)
814{
815  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
816  if ( tracks ) *tracks = f->tracks;
817  if ( heads ) *heads = f->heads;
818  if ( sectors ) *sectors = 16;
819  return IMGTOOLERR_SUCCESS;
820}
821
822static imgtoolerr_t thom_read_sector(imgtool_image* img, UINT32 track,
823                 UINT32 head, UINT32 sector, void *buf,
824                 size_t len)
825{
826  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
827  if ( head >= f->heads || sector < 1 || sector > 16 || track >= f->tracks )
828    return IMGTOOLERR_SEEKERROR;
829  if ( len > f->sector_size) return IMGTOOLERR_READERROR;
830  memcpy( buf, thom_get_sector( f, head, track, sector ), len );
831  return IMGTOOLERR_SUCCESS;
832}
833
834static imgtoolerr_t thom_write_sector(imgtool_image *img, UINT32 track,
835                  UINT32 head, UINT32 sector,
836                  const void *buf, size_t len)
837{
838  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
839  if ( stream_isreadonly( f->stream ) ) return IMGTOOLERR_WRITEERROR;
840  if ( head >= f->heads || sector < 1 || sector > 16 || track >= f->tracks )
841    return IMGTOOLERR_SEEKERROR;
842  if ( len > f->sector_size) return IMGTOOLERR_WRITEERROR;
843  f->modified = 1;
844  memcpy( thom_get_sector( f, head, track, sector ), buf, len );
845  return IMGTOOLERR_SUCCESS;
846}
847
848/* returns floopy name */
849/* actually, each side has its own name, but we only return the one on side 0.
850 */
851static void thom_info(imgtool_image *img, char *string, size_t len)
852{
853  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
854  UINT8* base = thom_get_sector( f, 0, 20, 1 );
855  char buf[9];
856  memcpy( buf, base, 8 );
857  buf[8] = 0;
858  thom_stringify( buf );
859  strncpy( string, buf, len );
860}
861
862/* each side of a floppy has its own filesystem, we treat them as'partitions'
863 */
864static imgtoolerr_t thom_list_partitions(imgtool_image *img,
865                imgtool_partition_info *partitions,
866                size_t len)
867{
868  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
869  if ( len >= 1 ) {
870    partitions[0].get_info = thom_basic_get_info;
871    partitions[0].base_block = 0;
872    partitions[0].block_count = 1;
873  }
874  if ( len >= 2 && f->heads >= 2 ) {
875    partitions[1].get_info = thom_basic_get_info;
876    partitions[1].base_block = 1;
877    partitions[1].block_count = 1;
878  }
879  return IMGTOOLERR_SUCCESS;
880}
881
882static imgtoolerr_t thom_open_partition(imgtool_partition *part,
883               UINT64 first_block, UINT64 block_count)
884{
885  imgtool_image* img = imgtool_partition_image( part );
886  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
887  if ( first_block >= f->heads )
888    return IMGTOOLERR_INVALIDPARTITION;
889  * ( (int*) imgtool_partition_extra_bytes( part ) ) = first_block;
890  return IMGTOOLERR_SUCCESS;
891}
892
893
894static imgtoolerr_t thom_begin_enum(imgtool_directory *enumeration,
895                const char *path)
896{
897  int* n = (int*) imgtool_directory_extrabytes( enumeration );
898  *n = 0;
899  return IMGTOOLERR_SUCCESS;
900}
901
902static imgtoolerr_t thom_next_enum(imgtool_directory *enumeration,
903               imgtool_dirent *ent)
904{
905  imgtool_partition *part = imgtool_directory_partition( enumeration);
906  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
907  imgtool_image* img = imgtool_partition_image( part );
908  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
909  int* n = (int*) imgtool_directory_extrabytes( enumeration );
910  thom_dirent d;
911
912  do {
913    thom_get_dirent( f, head, *n, &d );
914    (*n) ++;
915  }
916  while ( d.type == THOM_DIRENT_FREE );
917  if ( d.type == THOM_DIRENT_END ) ent->eof = 1;
918  else if ( d.type == THOM_DIRENT_INVALID ) {
919    ent->corrupt = 1;
920  }
921  else {
922    int size;
923    snprintf( ent->filename, sizeof(ent->filename), "%s.%s", d.name, d.ext );
924    snprintf( ent->attr, sizeof(ent->attr), "%c %c %s",
925         (d.ftype == 0) ? 'B' :  (d.ftype == 1) ? 'D' :
926         (d.ftype == 2) ? 'M' :  (d.ftype == 3) ? 'A' : '?',
927         (d.format == 0) ? 'B' : (d.format == 0xff) ? 'A' : '?',
928         d.comment );
929    ent->creation_time = thom_crack_time( &d );
930    size  = thom_get_file_size( f, head, &d );
931    if ( size >= 0 ) ent->filesize = size;
932    else {
933      ent->filesize = 0;
934      ent->corrupt = 1;
935    }
936  }
937  return IMGTOOLERR_SUCCESS;
938}
939
940static imgtoolerr_t thom_free_space(imgtool_partition *part, UINT64 *size)
941{
942  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
943  imgtool_image* img = imgtool_partition_image( part );
944  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
945  int nb = thom_get_free_blocks( f, head );
946  (*size) = nb * f->sectuse_size * 8;
947  return IMGTOOLERR_SUCCESS;
948}
949
950static imgtoolerr_t thom_read_file(imgtool_partition *part,
951               const char *filename,
952               const char *fork,
953               imgtool_stream *destf)
954{
955  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
956  imgtool_image* img = imgtool_partition_image( part );
957  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
958  thom_dirent d;
959  char name[9], ext[4], fname[14];
960  int size;
961
962  /* convert filename */
963  thom_conv_filename( filename, name, ext );
964  sprintf( fname, "%s.%s", name, ext );
965
966  if ( ! thom_find_dirent( f, head, fname, &d ) )
967    return IMGTOOLERR_FILENOTFOUND;
968  size = thom_get_file_size( f, head, &d );
969  if ( size < 0 ) return IMGTOOLERR_CORRUPTFILE;
970  thom_get_file( f, head, &d, destf );
971  return IMGTOOLERR_SUCCESS;
972}
973
974static imgtoolerr_t thom_delete_file(imgtool_partition *part,
975                 const char *filename)
976{
977  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
978  imgtool_image* img = imgtool_partition_image( part );
979  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
980  thom_dirent d;
981  char name[9], ext[4], fname[14];
982
983  /* convert filename */
984  thom_conv_filename( filename, name, ext );
985  sprintf( fname, "%s.%s", name, ext );
986 
987  if ( ! thom_find_dirent( f, head, fname, &d ) )
988    return IMGTOOLERR_FILENOTFOUND;
989  /*if ( thom_get_file_size( f, head, &d ) < 0 ) return IMGTOOLERR_CORRUPTFILE;*/
990  if ( stream_isreadonly( f->stream ) ) return IMGTOOLERR_WRITEERROR;
991  thom_del_file( f, head, &d );
992  return IMGTOOLERR_SUCCESS;
993}
994
995static imgtoolerr_t thom_write_file(imgtool_partition *part,
996                const char *filename,
997                const char *fork,
998                imgtool_stream *sourcef,
999                option_resolution *opts)
1000{
1001  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
1002  imgtool_image* img = imgtool_partition_image( part );
1003  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
1004  thom_dirent d;
1005  int size = stream_size( sourcef );
1006  int blocks = thom_get_free_blocks( f, head );
1007  char name[9], ext[4], fname[14];
1008  const char* comment;
1009  int is_new = 1;
1010
1011  if ( stream_isreadonly( f->stream ) ) return IMGTOOLERR_WRITEERROR;
1012
1013  /* convert filename */
1014  thom_conv_filename( filename, name, ext );
1015  sprintf( fname, "%s.%s", name, ext );
1016
1017  /* check available space & find dir entry */
1018  if ( thom_find_dirent( f, head, fname, &d ) ) {
1019    /* file already exists: delete it */
1020    if ( thom_get_file_size( f, head, &d ) < 0 ) return IMGTOOLERR_CORRUPTFILE;
1021    blocks += thom_get_file_blocks( f, head, &d );
1022    if ( blocks * 8 * f->sectuse_size < size ) return IMGTOOLERR_NOSPACE;
1023    thom_del_file( f, head, &d );
1024    is_new = 0;
1025  }
1026  else {
1027    /* new file, need new dir entry */
1028    if ( blocks * 8 * f->sectuse_size < size ) return IMGTOOLERR_NOSPACE;
1029    if ( ! thom_find_free_dirent( f, head, &d ) ) return IMGTOOLERR_NOSPACE;
1030    thom_make_time_now( &d );
1031  }
1032
1033  /* fill-in dir entry */
1034  memcpy( d.name, name, 9 );
1035  memcpy( d.ext, ext, 4 );
1036
1037  /* file type */
1038  switch ( option_resolution_lookup_int( opts, 'T' ) ) {
1039  case 0:
1040    if ( ! is_new ) break;
1041    if ( ! mame_stricmp( ext, "BAS" ) ) d.ftype = 0;
1042    else if ( ! mame_stricmp( ext, "BAT" ) ) d.ftype = 0;
1043    else if ( ! mame_stricmp( ext, "DAT" ) ) d.ftype = 1;
1044    else if ( ! mame_stricmp( ext, "ASC" ) ) d.ftype = 1;
1045    else if ( ! mame_stricmp( ext, "BIN" ) ) d.ftype = 2;
1046    else if ( ! mame_stricmp( ext, "MAP" ) ) d.ftype = 2;
1047    else if ( ! mame_stricmp( ext, "CFG" ) ) d.ftype = 2;
1048    else if ( ! mame_stricmp( ext, "ASM" ) ) d.ftype = 3;
1049    else d.ftype = 2;
1050    break;
1051  case 1: d.ftype = 0; break;
1052  case 2: d.ftype = 1; break;
1053  case 3: d.ftype = 2; break;
1054  case 4: d.ftype = 3; break;
1055  }
1056
1057 /* format flag */
1058 switch ( option_resolution_lookup_int( opts, 'F' ) ) {
1059  case 0:
1060    if ( ! is_new ) break;
1061    if ( ! mame_stricmp( ext, "DAT" ) ) d.format = 0xff;
1062    else if ( ! mame_stricmp( ext, "ASC" ) ) d.format = 0xff;
1063    else if ( ! mame_stricmp( ext, "ASM" ) ) d.format = 0xff;
1064    else d.format = 0;
1065    break;
1066  case 1: d.format = 0; break;
1067  case 2: d.format = 0xff; break;
1068  }
1069 
1070 /* comment */
1071 comment = option_resolution_lookup_string( opts, 'C' );
1072 if ( comment && *comment )
1073   strncpy( d.comment, comment, 8 );
1074
1075  /* write file */
1076 thom_put_file( f, head, &d, sourcef );
1077 return IMGTOOLERR_SUCCESS;
1078}
1079
1080static imgtoolerr_t thom_suggest_transfer(imgtool_partition *part,
1081                 const char *fname,
1082                 imgtool_transfer_suggestion *suggestions,
1083                 size_t suggestions_length)
1084{
1085  int head = *( (int*) imgtool_partition_extra_bytes( part ) );
1086  imgtool_image* img = imgtool_partition_image( part );
1087  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
1088  thom_dirent d;
1089  int is_basic = 0;
1090
1091  if ( suggestions_length < 1 ) return IMGTOOLERR_SUCCESS;
1092
1093  if ( fname ) {
1094    if ( ! thom_find_dirent( f, head, fname, &d ) )
1095      return IMGTOOLERR_FILENOTFOUND;
1096    if ( d.ftype == 0 && d.format == 0 ) is_basic = 1;
1097  }
1098
1099  if ( is_basic ) {
1100    suggestions[0].viability = SUGGESTION_RECOMMENDED;
1101    suggestions[0].filter = filter_thombas128_getinfo;
1102    if ( suggestions_length >= 2 ) {
1103      suggestions[1].viability = SUGGESTION_POSSIBLE;
1104      suggestions[1].filter = filter_thombas7_getinfo;
1105    }
1106    if ( suggestions_length >= 3 ) {
1107      suggestions[2].viability = SUGGESTION_POSSIBLE;
1108      suggestions[2].filter = filter_thombas5_getinfo;
1109    }
1110    if ( suggestions_length >= 4 ) {
1111      suggestions[3].viability = SUGGESTION_POSSIBLE;
1112      suggestions[3].filter = NULL;
1113    }
1114  }
1115  else {
1116    suggestions[0].viability = SUGGESTION_RECOMMENDED;
1117    suggestions[0].filter = NULL;
1118  }
1119
1120  return IMGTOOLERR_SUCCESS;
1121}
1122
1123static imgtoolerr_t thom_create(imgtool_image* img,
1124            imgtool_stream *stream,
1125            option_resolution *opts)
1126{
1127  thom_floppy* f = (thom_floppy*) imgtool_image_extra_bytes( img );
1128  int i;
1129  UINT8* buf;
1130  const char* name;
1131
1132  f->stream = stream;
1133  f->modified = 0;
1134
1135  /* get parameters */
1136  f->heads = option_resolution_lookup_int( opts, 'H' );
1137  f->tracks = option_resolution_lookup_int( opts, 'T' );
1138  name = option_resolution_lookup_string( opts, 'N' );
1139  switch ( option_resolution_lookup_int( opts, 'D' ) ) {
1140  case 0: f->sector_size = 128; f->sectuse_size = 128; break;
1141  case 1: f->sector_size = 256; f->sectuse_size = 255; break;
1142  default: return IMGTOOLERR_PARAMCORRUPT;
1143  }
1144
1145  /* sanity checks */
1146  switch ( f->tracks ) {
1147  case 25: if ( f->sector_size != 128 ) return IMGTOOLERR_PARAMCORRUPT; break;
1148  case 40: break;
1149  case 80: if ( f->sector_size != 256 ) return IMGTOOLERR_PARAMCORRUPT; break;
1150  default: return IMGTOOLERR_PARAMCORRUPT;
1151  }
1152
1153  memset( f->data, 0xe5, sizeof( f->data ) );
1154
1155  for ( i = 0; i < f->heads; i++ ) {
1156
1157    /* disk info */
1158    buf = thom_get_sector( f, i, 20, 1 );
1159    memset( buf, 0xff, f->sector_size );
1160    if ( name ) {
1161      strncpy( (char*)buf, name, 8 );
1162      thom_unstringity( (char*)buf, 8 );
1163    }
1164    else memset( buf, ' ', 8 );
1165   
1166    /* FAT */
1167    buf = thom_get_sector( f, i, 20, 2 );
1168    memset( buf, 0, f->sector_size );
1169    memset( buf + 1, 0xff, thom_nb_blocks( f ) );
1170    buf[ 41 ] = buf[ 42 ] = 0xfe; /* reserved for FAT */
1171   
1172    /* (empty) directory */
1173    buf = thom_get_sector( f, i, 20, 3 );
1174    memset( buf, 0xff, 14 * f->sector_size );
1175  }
1176
1177  f->modified = 1;
1178
1179  return IMGTOOLERR_SUCCESS;
1180}
1181
1182
1183/****************** BASIC tokenization *********************/
1184
1185/* character codes >= 128 are reserved for BASIC keywords */
1186
1187static const char* thombas7[2][128] = {
1188  { /* statements */
1189    "END", "FOR", "NEXT", "DATA", "DIM", "READ", "LET", "GO", "RUN", "IF",
1190    "RESTORE", "RETURN", "REM", "'", "STOP", "ELSE", "TRON", "TROFF", "DEFSTR",
1191    "DEFINT", "DEFSNG", "DEFDBL", "ON", "WAIT", "ERROR", "RESUME", "AUTO",
1192    "DELETE", "LOCATE", "CLS", "CONSOLE", "PSET", "MOTOR", "SKIP", "EXEC",
1193    "BEEP", "COLOR", "LINE", "BOX", "UNMASK", "ATTRB", "DEF", "POKE", "PRINT",
1194    "CONT", "LIST", "CLEAR", "WHILE", "WHEN", "NEW", "SAVE", "LOAD", "MERGE",
1195    "OPEN", "CLOSE", "INPEN", "PEN", "PLAY", "TAB(", "TO", "SUB", "FN",
1196    "SPC(", "USING", "USR", "ERL", "ERR", "OFF", "THEN", "NOT", "STEP",
1197    "+", "-", "*", "/", "^", "AND", "OR", "XOR", "EQV", "IMP", "MOD", "@",
1198    ">", "=", "<",
1199    /* DOS specific */
1200    "DSKINI", "DSKO$", "KILL", "NAME", "FIELD", "LSET", "RSET",
1201    "PUT", "GET", "VERIFY", "DEVICE", "DIR", "FILES", "WRITE", "UNLOAD",
1202    "BACKUP", "COPY", "CIRCLE", "PAINT", "DRAW", "RENUM", "SWAP", "DENSITY",
1203  },
1204  { /* functions: 0xff prefix */
1205    "SGN", "INT", "ABS", "FRE", "SQR", "LOG", "EXP", "COS", "SIN",
1206    "TAN", "PEEK", "LEN", "STR$", "VAL", "ASC", "CHR$", "EOF", "CINT", "CSNG",
1207    "CDBL", "FIX", "HEX$", "OCT$", "STICK", "STRIG", "GR$", "LEFT$", "RIGHT$",
1208    "MID$", "INSTR", "VARPTR", "RND", "INKEY$", "INPUT", "CSRLIN", "POINT",
1209    "SCREEN", "POS", "PTRIG",
1210    /* DOS specific */
1211    "DSKL", "CVI", "CVS", "CVD", "MKI$", "MKS$", "MKD$", "LOC", "LOF",
1212    "SPACE$", "STRING$", "DSKI$",
1213  }
1214};
1215
1216/* MO5: some keywords ar missing; DOS and TUNE are added */
1217static const char* thombas5[2][128] = {
1218  { /* statements */
1219    "END", "FOR", "NEXT", "DATA", "DIM", "READ", NULL, "GO", "RUN", "IF",
1220    "RESTORE", "RETURN", "REM", "'", "STOP", "ELSE", "TRON", "TROFF", "DEFSTR",
1221    "DEFINT", "DEFSNG", NULL, "ON", "TUNE", "ERROR", "RESUME", "AUTO",
1222    "DELETE", "LOCATE", "CLS", "CONSOLE", "PSET", "MOTOR", "SKIP", "EXEC",
1223    "BEEP", "COLOR", "LINE", "BOX", NULL, "ATTRB", "DEF", "POKE", "PRINT",
1224    "CONT", "LIST", "CLEAR", "DOS", NULL, "NEW", "SAVE", "LOAD", "MERGE",
1225    "OPEN", "CLOSE", "INPEN", "PEN", "PLAY", "TAB(", "TO", "SUB", "FN",
1226    "SPC(", "USING", "USR", "ERL", "ERR", "OFF", "THEN", "NOT", "STEP",
1227    "+", "-", "*", "/", "^", "AND", "OR", "XOR", "EQV", "IMP", "MOD", "@",
1228    ">", "=", "<",
1229    /* DOS specific */
1230    "DSKINI", "DSKO$", "KILL", "NAME", "FIELD", "LSET", "RSET",
1231    "PUT", "GET", "VERIFY", "DEVICE", "DIR", "FILES", "WRITE", "UNLOAD",
1232    "BACKUP","COPY", "CIRCLE", "PAINT", "DRAW", "RENUM", "SWAP", "SEARCH",
1233    "DENSITY",
1234  },
1235  { /* functions: 0xff prefix */
1236    "SGN", "INT", "ABS", "FRE", "SQR", "LOG", "EXP", "COS", "SIN",
1237    "TAN", "PEEK", "LEN", "STR$", "VAL", "ASC", "CHR$", "EOF", "CINT", NULL,
1238    NULL, "FIX", "HEX$", NULL, "STICK", "STRIG", "GR$", "LEFT$", "RIGHT$",
1239    "MID$", "INSTR", "VARPTR", "RND", "INKEY$", "INPUT", "CSRLIN", "POINT",
1240    "SCREEN", "POS", "PTRIG",
1241    /* DOS specific */
1242    "DSKL", "CVI", "CVS", "CVD", "MKI$", "MKS$", "MKD$", "LOC", "LOF",
1243    "SPACE$", "STRING$", "DSKI$",
1244  }
1245};
1246
1247/* BASIC 128 has many new keywords */
1248/* DENSITY is missing on BASIC 512 & BASIC 128 for MO6 but, otherwise, they
1249   have the same tokens
1250*/
1251static const char* thombas128[2][128] = {
1252  { /* statements */
1253    "END", "FOR", "NEXT", "DATA", "DIM", "READ", "LET", "GO", "RUN", "IF",
1254    "RESTORE", "RETURN", "REM", "'", "STOP", "ELSE", "TRON", "TROFF", "DEFSTR",
1255    "DEFINT", "DEFSNG", "DEFDBL", "ON", "WAIT", "ERROR", "RESUME", "AUTO",
1256    "DELETE", "LOCATE", "CLS", "CONSOLE", "PSET", "MOTOR", "SKIP", "EXEC",
1257    "BEEP", "COLOR", "LINE", "BOX", "UNMASK", "ATTRB", "DEF", "POKE", "PRINT",
1258    "CONT", "LIST", "CLEAR", "INTERVAL", "KEY", "NEW", "SAVE", "LOAD", "MERGE",
1259    "OPEN", "CLOSE", "INPEN", "PEN", "PLAY", "TAB(", "TO", "SUB", "FN",
1260    "SPC(", "USING", "USR", "ERL", "ERR", "OFF", "THEN", "NOT", "STEP",
1261    "+", "-", "*", "/", "^", "AND", "OR", "XOR", "EQV", "IMP", "MOD", "@",
1262    ">", "=", "<",
1263    "DSKINI", "DSKO$", "KILL", "NAME", "FIELD", "LSET", "RSET",
1264    "PUT", "GET", "VERIFY", "DEVICE", "DIR", "FILES", "WRITE", "UNLOAD",
1265    "BACKUP", "COPY", "CIRCLE", "PAINT", "RESET", "RENUM", "SWAP", "DENSITY",
1266    "WINDOW", "PATTERN", "DO", "LOOP", "EXIT", "INMOUSE", "MOUSE", "CHAINE",
1267    "COMMON", "SEARCH", "FWD", "TURTLE",
1268  },
1269  { /* functions: 0xff prefix */
1270    "SGN", "INT", "ABS", "FRE", "SQR", "LOG", "EXP", "COS", "SIN",
1271    "TAN", "PEEK", "LEN", "STR$", "VAL", "ASC", "CHR$", "EOF", "CINT", "CSNG",
1272    "CDBL", "FIX", "HEX$", "OCT$", "STICK", "STRIG", "GR$", "LEFT$", "RIGHT$",
1273    "MID$", "INSTR", "VARPTR", "RND", "INKEY$", "INPUT", "CSRLIN", "POINT",
1274    "SCREEN", "POS", "PTRIG",
1275    "DSKL", "CVI", "CVS", "CVD", "MKI$", "MKS$", "MKD$", "LOC", "LOF",
1276    "SPACE$", "STRING$", "DSKI$",
1277    "FKEY$", "MIN(", "MAX(", "ATN", "CRUNCH$", "MTRIG", "EVAL", "PALETTE",
1278    "BANK", "HEAD", "ROT", "SHOW", "ZOOM", "TRACE",
1279  }
1280};
1281
1282/* tables for simple XOR encryption sieve */
1283static const UINT8 crypt1[11] = {
1284  0x80, 0x19, 0x56, 0xAA, 0x80, 0x76, 0x22, 0xF1,  0x82, 0x38, 0xAA
1285};
1286
1287static const UINT8 crypt2[13] = {
1288  0x86, 0x1E, 0xD7, 0xBA, 0x87, 0x99, 0x26, 0x64, 0x87, 0x23, 0x34, 0x58, 0x86
1289};
1290
1291/* decrypt BASIC protected files */
1292static void thom_decrypt(imgtool_stream* out, imgtool_stream* in)
1293{
1294  int i1 = 11, i2 = 13;
1295  while ( 1 ) {
1296    UINT8 b;
1297    if ( stream_read( in, &b, 1) < 1 ) break;
1298    b = ( (UINT8)(b - i2) ^ crypt2[i2-1] ^ crypt1[i1-1] ) + i1;
1299    stream_putc( out, b );
1300    i1--; i2--;
1301    if ( !i1 ) i1 = 11;
1302    if ( !i2 ) i2 = 13;
1303  }
1304}
1305
1306/* encrypt BASIC protected files */
1307static void thom_encrypt(imgtool_stream* out, imgtool_stream* in)
1308{
1309  int i1 = 11, i2 = 13;
1310  while ( 1 ) {
1311    UINT8 b;
1312    if ( stream_read( in, &b, 1) < 1 ) break;
1313    b = ( (UINT8)(b - i1) ^ crypt2[i2-1] ^ crypt1[i1-1] ) + i2;
1314    stream_putc( out, b );
1315    i1--; i2--;
1316    if ( !i1 ) i1 = 11;
1317    if ( !i2 ) i2 = 13;
1318  }
1319}
1320
1321static imgtoolerr_t thomcrypt_read_file(imgtool_partition *part,
1322               const char *name,
1323               const char *fork, imgtool_stream *dst)
1324{
1325  UINT8 buf[3];
1326  imgtool_stream *org = stream_open_mem( NULL, 0 );
1327  imgtoolerr_t err;
1328  if ( !org ) return IMGTOOLERR_OUTOFMEMORY;
1329
1330  /* read file */
1331  err = thom_read_file( part, name, fork, org );
1332  if ( err ) {
1333    stream_close( org );
1334    return err;
1335  }
1336
1337  stream_seek( org, 0, SEEK_SET );
1338  if ( stream_read( org, buf, 3 ) < 3 || buf[0] != 0xfe ) {
1339    /* regular file */
1340    stream_seek( org, 0, SEEK_SET );
1341    stream_transfer_all( dst, org );
1342  }
1343  else {
1344    /* encrypted file */
1345    stream_putc( dst, 0xff );
1346    stream_write( dst, buf+1, 2 );
1347    thom_decrypt( dst, org );
1348  }
1349
1350  stream_close( org );
1351  return IMGTOOLERR_SUCCESS;
1352}
1353
1354static imgtoolerr_t thomcrypt_write_file(imgtool_partition *part,
1355                const char *name,
1356                const char *fork, imgtool_stream *src,
1357                option_resolution *opts)
1358{
1359  UINT8 buf[3];
1360 
1361  if ( stream_read( src, buf, 3 ) < 3 || buf[0] == 0xfe ) {
1362    /* too short or already encrypted file */
1363    stream_seek( src, 0, SEEK_SET );
1364    return thom_write_file( part, name, fork, src, opts );
1365  }
1366  else {
1367    /* regular file */
1368    imgtool_stream *dst = stream_open_mem( NULL, 0 );
1369    imgtoolerr_t err;
1370    if ( !dst ) return IMGTOOLERR_OUTOFMEMORY;
1371    stream_putc( dst, 0xfe );
1372    stream_write( dst, buf+1, 2 );
1373    thom_encrypt( dst, src );
1374    stream_seek( dst, 0, SEEK_SET );
1375    err = thom_write_file( part, name, fork, dst, opts );
1376    stream_close( dst);
1377    return err;
1378  }
1379}
1380
1381void filter_thomcrypt_getinfo(UINT32 state, union filterinfo *info)
1382{
1383  switch(state) {
1384  case FILTINFO_STR_NAME:
1385    info->s = "thomcrypt";
1386    break;
1387  case FILTINFO_STR_HUMANNAME:
1388    info->s = "Thomson BASIC, Protected file encryption (no tokenization)";
1389    break;
1390  case FILTINFO_PTR_READFILE:
1391    info->read_file = thomcrypt_read_file;
1392    break;
1393  case FILTINFO_PTR_WRITEFILE:
1394    info->write_file = thomcrypt_write_file;
1395    break;
1396  }
1397}
1398
1399/* untokenization automatically decrypt protected files */
1400static imgtoolerr_t thom_basic_read_file(imgtool_partition *part,
1401                const char *name,
1402                const char *fork,
1403                imgtool_stream *dst,
1404                const char* table[2][128])
1405{
1406  imgtool_stream *org = stream_open_mem( NULL, 0 );
1407  imgtoolerr_t err;
1408  UINT8 buf[4];
1409  int i;
1410
1411  if ( !org ) return IMGTOOLERR_OUTOFMEMORY;
1412
1413  err = thomcrypt_read_file( part, name, fork, org );
1414  if ( err ) {
1415    stream_close( org );
1416    return err;
1417  }
1418  stream_seek( org, 3, SEEK_SET ); /* skip header */
1419
1420  while ( 1 ) {
1421    int in_str = 0, in_fun = 0;
1422    int linelength, linenum;
1423   
1424    /* line header: line length and line number */
1425    /* I am not sure this is 100% correct but it works in many cases */
1426    if ( stream_read( org, buf, 2 ) < 2 ) goto end;
1427    linelength = ((int)buf[0] << 8) + (int)buf[1] - 4;
1428    if ( linelength <= 0 ) goto end;
1429    if ( stream_read( org, buf, 2 ) < 2 ) goto end;
1430    linenum = ((int)buf[0] << 8) + buf[1];
1431    stream_printf( dst, "%u ", linenum );
1432
1433    /* process line */
1434    for ( i = 0; i < linelength; i++ ) {
1435      UINT8 c;
1436      if ( stream_read( org, &c, 1 ) < 1 ) break;
1437      if ( c == 0 ) {
1438   /* Sometimes, linelength seems wrong and we must rely on the fact that
1439      BASIC lines are 0-terminated.
1440      At other times, there are 0 embedded within lines or extra stuff
1441      between the 0 and the following line, and so, we must rely
1442      on linelength to cut the line (!)
1443   */
1444   if ( linelength > 256 ) break;
1445      }
1446      else if ( c == 0xff && ! in_str ) in_fun = 1; /* function prefix */
1447      else {
1448   if ( c >= 0x80 && ! in_str ) {
1449     /* token */
1450     const char* token = table[ in_fun ][ c - 0x80 ];
1451     if ( token ) stream_puts( dst, token );
1452     else stream_puts( dst, "???" );
1453   }
1454   else {
1455     /* regular character */
1456     if ( c == '"' ) in_str = 1 - in_str;
1457     stream_putc( dst, c ); /* normal letter */
1458   }
1459   in_fun = 0;
1460      }
1461    }
1462    stream_putc( dst, '\n' );
1463  }
1464  end:
1465
1466  stream_close( org );
1467  return IMGTOOLERR_SUCCESS;
1468}
1469
1470static imgtoolerr_t thom_basic_write_file(imgtool_partition *part,
1471                const char *name,
1472                const char *fork,
1473                imgtool_stream *src,
1474                option_resolution *opts,
1475                const char* table[2][128])
1476{
1477  return IMGTOOLERR_UNIMPLEMENTED;
1478}
1479
1480
1481#define FILTER(short,long)                  \
1482  static imgtoolerr_t short##_read_file(imgtool_partition *part,   \
1483               const char *name,      \
1484               const char *fork,      \
1485               imgtool_stream *dst)      \
1486  {                           \
1487    return thom_basic_read_file( part, name, fork, dst, short );   \
1488  }                           \
1489  static imgtoolerr_t short##_write_file(imgtool_partition *part,   \
1490                const char *name,      \
1491                const char *fork,      \
1492                imgtool_stream *src,      \
1493                option_resolution *opts)   \
1494  {                           \
1495    return thom_basic_write_file( part, name, fork, src, opts, short );   \
1496  }                           \
1497  void filter_##short##_getinfo(UINT32 state, union filterinfo *info)   \
1498  {                           \
1499    switch(state)                     \
1500      {                           \
1501      case FILTINFO_STR_NAME:                  \
1502   info->s = #short;                  \
1503   break;                        \
1504      case FILTINFO_STR_HUMANNAME:               \
1505   info->s = long;                     \
1506   break;                        \
1507      case FILTINFO_PTR_READFILE:               \
1508   info->read_file = short##_read_file;            \
1509   break;                        \
1510      case FILTINFO_PTR_WRITEFILE:               \
1511   info->write_file = short##_write_file;            \
1512   break;                        \
1513      }                           \
1514  }
1515
1516FILTER( thombas5,   
1517   "Thomson MO5 w/ BASIC 1.0, Tokenized Files (read-only, auto-decrypt)" )
1518FILTER( thombas7,   
1519   "Thomson TO7 w/ BASIC 1.0, Tokenized Files (read-only, auto-decrypt)" )
1520FILTER( thombas128,
1521   "Thomson w/ BASIC 128/512, Tokenized Files (read-only, auto-decrypt)" )
1522
1523
1524/************************* driver ***************************/
1525
1526OPTION_GUIDE_START( thom_createimage_optguide )
1527  OPTION_INT( 'H', "heads", "Heads" )
1528  OPTION_INT( 'T', "tracks", "Tracks" )
1529  OPTION_ENUM_START( 'D', "density", "Density" )
1530    OPTION_ENUM( 0, "SD", "Single density (128 bytes)" )
1531    OPTION_ENUM( 1, "DD", "Double density (256 bytes)" )
1532  OPTION_ENUM_END
1533  OPTION_STRING( 'N', "name", "Floppy name" )
1534OPTION_GUIDE_END
1535
1536OPTION_GUIDE_START( thom_writefile_optguide )
1537  OPTION_ENUM_START( 'T', "ftype", "File type" )
1538    OPTION_ENUM( 0, "auto", "Automatic (by extension)" )
1539    OPTION_ENUM( 1, "B", "Program" )
1540    OPTION_ENUM( 2, "D", "Data" )
1541    OPTION_ENUM( 3, "M", "Machine Code" )
1542    OPTION_ENUM( 4, "A",  "Assembler Source" )
1543  OPTION_ENUM_END
1544  OPTION_ENUM_START( 'F', "format", "Format flag" )
1545    OPTION_ENUM( 0, "auto",   "Automatic (by extension)" )
1546    OPTION_ENUM( 1, "B", "Binary, Tokenized BASIC" )
1547    OPTION_ENUM( 2, "A", "ASCII" )
1548  OPTION_ENUM_END
1549  OPTION_STRING( 'C', "comment", "Comment" )
1550OPTION_GUIDE_END
1551
1552static void thom_basic_get_info(const imgtool_class *clas,
1553            UINT32 param,
1554            union imgtoolinfo *info)
1555{
1556  switch ( param ) {
1557
1558  case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:
1559    info->i = sizeof(thom_floppy); break;
1560  case IMGTOOLINFO_INT_PARTITION_EXTRA_BYTES:
1561    info->i = sizeof(int); break;
1562  case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:
1563    info->i = sizeof(int); break;
1564  case IMGTOOLINFO_INT_SUPPORTS_CREATION_TIME:
1565  case IMGTOOLINFO_INT_PREFER_UCASE:
1566    info->i = 1; break;
1567  case IMGTOOLINFO_INT_PATH_SEPARATOR:
1568    info->i = 0; break;
1569  case IMGTOOLINFO_STR_FILE:
1570    strcpy( info->s = imgtool_temp_str(), __FILE__ ); break;
1571  case IMGTOOLINFO_STR_NAME:
1572    strcpy( info->s = imgtool_temp_str(), "thom" ); break;
1573  case IMGTOOLINFO_STR_DESCRIPTION:
1574    strcpy( info->s = imgtool_temp_str(), "Thomson BASIC filesystem" );
1575    break;
1576  case IMGTOOLINFO_PTR_CREATE:
1577    info->create = thom_create; break;
1578  case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:
1579    info->createimage_optguide = thom_createimage_optguide; break;
1580  case IMGTOOLINFO_PTR_BEGIN_ENUM:
1581    info->begin_enum = thom_begin_enum; break;
1582  case IMGTOOLINFO_PTR_NEXT_ENUM:
1583    info->next_enum = thom_next_enum; break;
1584  case IMGTOOLINFO_PTR_READ_FILE:
1585    info->read_file = thom_read_file; break;
1586  case IMGTOOLINFO_PTR_WRITE_FILE:
1587    info->write_file = thom_write_file; break;
1588  case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE:
1589    info->writefile_optguide = thom_writefile_optguide; break;
1590  case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC:
1591    strcpy( info->s = imgtool_temp_str(), "T[0]-4;F[0]-2;C" ); break;
1592  case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:
1593    info->suggest_transfer = thom_suggest_transfer; break;
1594  case IMGTOOLINFO_PTR_DELETE_FILE:
1595    info->delete_file = thom_delete_file; break;
1596  case IMGTOOLINFO_PTR_FREE_SPACE:
1597    info->free_space = thom_free_space; break;
1598  case IMGTOOLINFO_PTR_GET_SECTOR_SIZE:
1599    info->get_sector_size = thom_get_sector_size; break;
1600  case IMGTOOLINFO_PTR_GET_GEOMETRY:
1601    info->get_geometry = thom_get_geometry; break;
1602  case IMGTOOLINFO_PTR_INFO:
1603    info->info = thom_info; break;
1604  case IMGTOOLINFO_PTR_READ_SECTOR:
1605    info->read_sector = thom_read_sector; break;
1606  case IMGTOOLINFO_PTR_WRITE_SECTOR:
1607    info->write_sector = thom_write_sector; break;
1608  case IMGTOOLINFO_PTR_LIST_PARTITIONS:
1609    info->list_partitions = thom_list_partitions; break;
1610  case IMGTOOLINFO_PTR_OPEN_PARTITION:
1611    info->open_partition = thom_open_partition; break;
1612  }
1613}
1614
1615void thom_fd_basic_get_info(const imgtool_class *clas,
1616             UINT32 param,
1617             union imgtoolinfo *info)
1618{
1619  switch ( param ) {
1620  case IMGTOOLINFO_STR_NAME:
1621    strcpy( info->s = imgtool_temp_str(), "thom_fd" ); break;
1622  case IMGTOOLINFO_STR_DESCRIPTION:
1623    strcpy( info->s = imgtool_temp_str(),
1624       "Thomson .fd disk image, BASIC format" );
1625    break;
1626  case IMGTOOLINFO_STR_FILE_EXTENSIONS:
1627    strcpy( info->s = imgtool_temp_str(), "fd" ); break;
1628  case IMGTOOLINFO_PTR_OPEN:
1629    info->open = thom_open_fd_qd; break;
1630  case IMGTOOLINFO_PTR_CLOSE:
1631    info->close = thom_close_fd_qd; break;
1632  case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:
1633    strcpy( info->s = imgtool_temp_str(), "H[1]-2;T40/[80];D0-[1];N" ); break;
1634  default:
1635    thom_basic_get_info( clas, param, info );
1636  }
1637}
1638
1639void thom_qd_basic_get_info(const imgtool_class *clas,
1640             UINT32 param,
1641             union imgtoolinfo *info)
1642{
1643  switch ( param ) {
1644  case IMGTOOLINFO_STR_NAME:
1645    strcpy( info->s = imgtool_temp_str(), "thom_qd" ); break;
1646  case IMGTOOLINFO_STR_DESCRIPTION:
1647    strcpy( info->s = imgtool_temp_str(),
1648       "Thomson .qd disk image, BASIC format" );
1649    break;
1650  case IMGTOOLINFO_STR_FILE_EXTENSIONS:
1651    strcpy( info->s = imgtool_temp_str(), "qd" ); break;
1652  case IMGTOOLINFO_PTR_OPEN:
1653    info->open = thom_open_fd_qd; break;
1654  case IMGTOOLINFO_PTR_CLOSE:
1655    info->close = thom_close_fd_qd; break;
1656  case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:
1657    strcpy( info->s = imgtool_temp_str(), "H[1]-2;T[25];D[0];N" ); break;
1658  default:
1659    thom_basic_get_info( clas, param, info );
1660  }
1661}
1662
1663void thom_sap_basic_get_info(const imgtool_class *clas,
1664              UINT32 param,
1665              union imgtoolinfo *info)
1666{
1667  switch ( param ) {
1668  case IMGTOOLINFO_STR_NAME:
1669    strcpy( info->s = imgtool_temp_str(), "thom_sap" ); break;
1670  case IMGTOOLINFO_STR_DESCRIPTION:
1671    strcpy( info->s = imgtool_temp_str(),
1672       "Thomson .sap disk image, BASIC format" );
1673    break;
1674  case IMGTOOLINFO_STR_FILE_EXTENSIONS:
1675    strcpy( info->s = imgtool_temp_str(), "sap" ); break;
1676  case IMGTOOLINFO_PTR_OPEN:
1677    info->open = thom_open_sap; break;
1678  case IMGTOOLINFO_PTR_CLOSE:
1679    info->close = thom_close_sap; break;
1680  case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:
1681    strcpy( info->s = imgtool_temp_str(), "H[1];T40/[80];D0-[1];N" ); break;
1682  default:
1683    thom_basic_get_info( clas, param, info );
1684  }
1685}
src/mess/tools/imgtool/modules/crt.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "zlib.h"
5#include "osdepend.h"
6#include "imgtoolx.h"
7
8#ifdef LSB_FIRST
9typedef struct {
10   unsigned char high, low;
11} biguword;
12typedef struct {
13   unsigned char highest, high, mid, low;
14} bigulong;
15#define GET_UWORD(a) (a.low|(a.high<<8))
16#define GET_ULONG(a) (a.low|(a.mid<<8)|(a.high<<16)|(a.highest<<24))
17#define SET_UWORD(a,v) a.low=(v)&0xff;a.high=((v)>>8)&0xff
18#define SET_ULONG(a,v) a.low=(v)&0xff;a.mid=((v)>>8)&0xff;a.high=((v)>>16)&0xff;a.highest=((v)>>24)&0xff
19#else
20typedef UINT32 bigulong;
21typedef UINT16 biguword;
22#define GET_UWORD(a) a
23#define GET_ULONG(a) a
24#define SET_UWORD(a,v) a=v
25#define SET_ULONG(a,v) a=v
26#endif
27
28/* format description found in the ccs64 emulator
29
30CARTRIDGE FILE FORMAT FOR CCS64 (using fileextension .CRT)
31
320000 'C64 CARTRIDGE '
330010 ULONG fileheader-length (counted from offset 0000, default=0040)
340014 UWORD Version (=0100)
350016 UWORD Hardware type
360018 UBYTE Exrom line
370019 UBYTE Game line
38001A UBYTE[6] For future use...
390020 UBYTE[20] Name (null-terminated string)
400040 Chip Packets
41...
42
43Chip Packets:
44
450000 'CHIP'
460004 ULONG packetlength (counted from offset 0000)
470008 UWORD chiptype
48000A UWORD bank (for normal cartridges = 0)
49000C UWORD address
50000E UWORD length
510010 UBYTE[] data
52...
53Hardware Types:
54
550 - Normal cartridge
561 - Action Replay
572 - KCS Power Cartridge
583 - Final Cartridge III
594 - Simons Basic
605 - Ocean type 1 (256 and 128 Kb)
616 - Expert Cartridge
627 - Fun Play
638 - Super Games
649 - Atomic Power
6510 - Epyx Fastload
6611 - Westermann
67
68
69Chip Types:
70
710 - ROM
721 - RAM, no data field
732 - Flash ROM
74
75
76All UWORD and ULONG's are in (MSB,LSB) format, i.e. $1234 will be $12,$34 in bytes.
77
78EXAMPLE FOR ACTION REPLAY CARTRIDGE
79
80$0000: 'C64 CARTRIDGE   '
81$0010: 00 00 00 40  01 00 00 01  00 00 00 00  00 00 00 00
82$0020: 'Action Replay V' 00
83$0030: 00 00 ... 00
84
85$0040: 'CHIP'
86$0044: 00 00 20 10  00 00 00 00  80 00 20 00
87$0050: <data 8192 bytes for bank 0>...
88
89$2050: 'CHIP'
90$2054: 00 00 20 10  00 00 00 01  80 00 20 00
91$2060: <data 8192 bytes for bank 1>...
92
93$4060: 'CHIP'
94$4064: 00 00 20 10  00 00 00 02  80 00 20 00
95$4070: <data 8192 bytes for bank 2>...
96
97$6070: 'CHIP'
98$6074: 00 00 20 10  00 00 00 03  80 00 20 00
99$6080: <data 8192 bytes for bank 3>...
100
101$8080:
102
103 
104
105EXAMPLE FOR KCS POWER CARTRIDGE
106
107$0000: 'C64 CARTRIDGE   '
108$0010: 00 00 00 40  01 00 00 02  00 00 00 00  00 00 00 00
109$0020: 'KCS Power Cartridge' 00
110$0030: 00 00 ... 00
111
112$0040: 'CHIP'
113$0044: 00 00 20 10  00 00 00 00  80 00 20 00
114$0050: <data 8192 bytes for 8000-9fff>...
115
116$2050: 'CHIP'
117$2054: 00 00 20 10  00 00 00 00  A0 00 20 00
118$2060: <data 8192 bytes for a000-bfff>...
119
120$4060:
121
122 
123
124EXAMPLE FOR FINAL CARTRIDGE III
125
126$0000: 'C64 CARTRIDGE   '
127$0010: 00 00 00 40  01 00 00 03  01 01 00 00  00 00 00 00
128$0020: 'Final cartridge' 00
129$0030: 00 00 ... 00
130
131$0040: 'CHIP'
132$0044: 00 00 40 10  00 00 00 00  80 00 40 00
133$0050: <data 16384 bytes for bank 0>...
134
135$4050: 'CHIP'
136$4054: 00 00 40 10  00 00 00 01  80 00 40 00
137$4060: <data 16384 bytes for bank 1>...
138
139$8060: 'CHIP'
140$8064: 00 00 40 10  00 00 00 02  80 00 40 00
141$8070: <data 16384 bytes for bank 2>...
142
143$C070: 'CHIP'
144$C074: 00 00 40 10  00 00 00 03  80 00 40 00
145$C080: <data 16384 bytes for bank 3>...
146
147$10080:
148
149 
150
151EXAMPLE FOR SIMONS BASIC
152
153$0000: 'C64 CARTRIDGE   '
154$0010: 00 00 00 40  01 00 00 04  00 01 00 00  00 00 00 00
155$0020: 'Simons Basic' 00
156$0030: 00 00 ... 00
157
158$0040: 'CHIP'
159$0044: 00 00 20 10  00 00 00 00  80 00 20 00
160$0050: <data 8192 bytes for 8000-9fff>...
161
162$2050: 'CHIP'
163$2054: 00 00 20 10  00 00 00 00  A0 00 20 00
164$2060: <data 8192 bytes for a000-bfff>...
165
166$4060:
167
168 
169
170EXAMPLE FOR OCEAN TYPE1
171
172$0000: 'C64 CARTRIDGE   '
173$0010: 00 00 00 40  01 00 00 05  00 00 00 00  00 00 00 00
174$0020: 'Robocop2' 00
175$0030: 00 00 ... 00
176
177$0040: 'CHIP'
178$0044: 00 00 20 10  00 00 00 00  80 00 20 00
179$0050: <data 8192 bytes for 8000-9fff, bank 0>...
180
181$2050: 'CHIP'
182$2054: 00 00 20 10  00 00 00 01  80 00 20 00
183$2060: <data 8192 bytes for 8000-9fff, bank 1>...
184...
185$20140: 'CHIP'
186$20144: 00 00 20 10  00 00 00 10  A0 00 20 00
187$20150: <data 8192 bytes for a000-bfff, bank 16>...
188
189$22150: 'CHIP'
190$22154: 00 00 20 10  00 00 00 11  A0 00 20 00
191$22160: <data 8192 bytes for a000-bfff, bank 17>...
192...
193$40240:
194
195 
196
197EXAMPLE FOR FUN PLAY TYPE
198
199$0000: 'C64 CARTRIDGE '
200$0010: 00 00 00 40 01 00 00 07 00 00 00 00 00 00 00 00
201$0020: 'FUN PLAY' 00 00 00 00 00 00 00 00
202$0030: 00 00 ... 00
203
204$0040: 'CHIP'
205$0044: 00 00 20 10 00 00 00 00 80 00 20 00
206$0050: <data 8192 bytes for 8000-9fff, bank 0>...
207
208$2050: 'CHIP'
209$2054: 00 00 20 10 00 00 00 08 80 00 20 00
210$2060: <data 8192 bytes for 8000-9fff, bank 1>...
211
212$4060: 'CHIP'
213$2054: 00 00 20 10 00 00 00 10 80 00 20 00
214$2060: <data 8192 bytes for 8000-9fff, bank 2>...
215...
216
217$1E130: 'CHIP'
218$1E134: 00 00 20 10 00 00 00 39 80 00 20 00
219$1E140: <data 8192 bytes for 8000-9fff, bank 15>...
220
221$20140:
222
223 
224
225EXAMPLE FOR SUPER GAMES TYPE
226
227$0000: 'C64 CARTRIDGE '
228$0010: 00 00 00 40 01 00 00 08 00 00 00 00 00 00 00 00
229$0020: 'SUPER GAMES' 00 00 00 00 00
230$0030: 00 00 ... 00
231
232$0040: 'CHIP'
233$0044: 00 00 40 10 00 00 00 00 80 00 40 00
234$0050: <data 16384 bytes for 8000-bfff, bank 0>...
235
236$4050: 'CHIP'
237$4054: 00 00 40 10 00 00 00 01 80 00 40 00
238$4060: <data 16384 bytes for 8000-bfff, bank 0>...
239
240$8060: 'CHIP'
241$8064: 00 00 40 10 00 00 00 02 80 00 40 00
242$8070: <data 16384 bytes for 8000-bfff, bank 0>...
243
244$C070: 'CHIP'
245$C074: 00 00 40 10 00 00 00 03 80 00 40 00
246$C080: <data 16384 bytes for 8000-bfff, bank 0>...
247
248$10080:
249
250 
251
252EXAMPLE FOR ATOMIC POWER CARTRIDGE
253
254$0000: 'C64 CARTRIDGE   '
255$0010: 00 00 00 40  01 00 00 09  00 00 00 00  00 00 00 00
256$0020: 'Atomic Power' 00
257$0030: 00 00 ... 00
258
259$0040: 'CHIP'
260$0044: 00 00 20 10  00 00 00 00  80 00 20 00
261$0050: <data 8192 bytes for bank 0>...
262
263$2050: 'CHIP'
264$2054: 00 00 20 10  00 00 00 01  80 00 20 00
265$2060: <data 8192 bytes for bank 1>...
266
267$4060: 'CHIP'
268$4064: 00 00 20 10  00 00 00 02  80 00 20 00
269$4070: <data 8192 bytes for bank 2>...
270
271$6070: 'CHIP'
272$6074: 00 00 20 10  00 00 00 03  80 00 20 00
273$6080: <data 8192 bytes for bank 3>...
274
275$8080:
276
277 
278
279EXAMPLE FOR EPYX FASTLOAD TYPE
280
281$0000: 'C64 CARTRIDGE '
282$0010: 00 00 00 40 01 00 00 0A 01 01 00 00 00 00 00 00
283$0020: 'EPYX FASTLOAD' 00 00 00
284$0030: 00 00 ... 00
285
286$0040: 'CHIP'
287$0044: 00 00 20 10 00 00 00 00 80 00 20 00
288$0050: <data 8192 bytes for 8000-9fff>
289
290$2050:
291
292 
293
294EXAMPLE FOR WESTERMANN TYPE
295
296$0000: 'C64 CARTRIDGE '
297$0010: 00 00 00 40 01 00 00 0A 00 01 00 00 00 00 00 00
298$0020: 'Westermann' 00 00 00
299$0030: 00 00 ... 00
300
301$0040: 'CHIP'
302$0044: 00 00 40 10 00 00 00 00 80 00 40 00
303$0050: <data 16384 bytes for 8000-bfff>
304
305$4050:
306*/
307 
308static const char *hardware_types[]={
309   "Normal cartridge",
310   "Action Replay",
311   "KCS Power Cartridge",
312   "Final Cartridge III",
313   "Simons Basic",
314   "Ocean type 1 (256 and 128 Kb)",
315   "Expert Cartridge",
316   "Fun Play",
317   "Super Games",
318   "Atomic Power",
319   "Epyx Fastload",
320   "Westermann"
321};
322typedef struct{
323   char id[0x10]; // C64 CARTRIDGE
324   bigulong length;
325   biguword version;
326   biguword hardware_type;
327   unsigned char exrom_line;
328   unsigned char game_line;
329   unsigned char reserved[6];
330   char name[0x20];
331} crt_header;
332   
333static const char *chip_types[]={ "ROM", "RAM", "FLASH" };
334typedef struct {
335   char id[4]; // CHIP
336   bigulong packet_length;
337   biguword chip_type;
338   biguword bank;
339   biguword address;
340   biguword length;
341} crt_packet;
342
343typedef struct {
344   imgtool_image base;
345   imgtool_stream *file_handle;
346   int size;
347   int modified;
348   unsigned char *data;
349} crt_image;
350
351#define HEADER(image) ((crt_header*)image->data)
352#define PACKET(image, pos) ((crt_packet*)(image->data+pos))
353
354typedef struct {
355   imgtool_directory base;
356   crt_image *image;
357   int pos;
358   int number;
359} crt_iterator;
360
361static int crt_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
362static void crt_image_exit(imgtool_image *img);
363static void crt_image_info(imgtool_image *img, char *string, const int len);
364static int crt_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
365static int crt_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
366static void crt_image_closeenum(imgtool_directory *enumeration);
367//static size_t crt_image_freespace(imgtool_image *img);
368static int crt_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
369static int crt_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *_options);
370static int crt_image_deletefile(imgtool_image *img, const char *fname);
371static int crt_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options);
372
373/*
374   IMAGE_USES_FTYPE|IMAGE_USES_FADDR|IMAGE_USES_FBANK
375   |IMAGE_USES_HARDWARE_TYPE|IMAGE_USES_GAME_LINE
376   |IMAGE_USES_EXROM_LINE|IMAGE_USES_LABEL, //flags
377*/
378
379static struct OptionTemplate c64crt_fileeopts[] =
380{
381   { "ftype",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,   0,      0xffff,   NULL   },   /* [0] */
382   { "faddr",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,   0,      0xffff,   NULL   },   /* [1] */
383   { "fbank",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,   0,      0xffff,   NULL   },   /* [2] */
384   { NULL, NULL, 0, 0, 0, 0 }
385};
386
387#define C64CRT_FILEOPTION_FTYPE      0
388#define C64CRT_FILEOPTION_FADDR      1
389#define C64CRT_FILEOPTION_FBANK      2
390
391static struct OptionTemplate c64crt_createopts[] =
392{
393   { "hardwaretype",   NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      0xffff,   NULL   },   /* [0] */
394   { "gameline",      NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      0x00ff,   NULL   },   /* [1] */
395   { "exromline",      NULL, IMGOPTION_FLAG_TYPE_INTEGER,                     0,      0x00ff,   NULL   },   /* [2] */
396   { "label",         NULL, IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,   0,      0,      NULL   },   /* [3] */
397   { NULL, NULL, 0, 0, 0, 0 }
398};
399
400#define C64CRT_CREATEOPTION_HARDWARETYPE   0
401#define C64CRT_CREATEOPTION_GAMELINE      1
402#define C64CRT_CREATEOPTION_EXROMLINE      2
403#define C64CRT_CREATEOPTION_LABEL         3
404
405IMAGEMODULE(
406   c64crt,
407   "Commodore 64 Cartridge",   /* human readable name */
408   "crt",                        /* file extension */
409   "c64.crc",                        /* crcfile */
410   "c64",                        /* crc system name */
411   NULL,                        /* eoln */
412   0,                           /* flags */
413   crt_image_init,            /* init function */
414   crt_image_exit,            /* exit function */
415   crt_image_info, /* info function */
416   crt_image_beginenum,         /* begin enumeration */
417   crt_image_nextenum,         /* enumerate next */
418   crt_image_closeenum,         /* close enumeration */
419   NULL, //crt_image_freespace,         /* free space on image */
420   crt_image_readfile,         /* read file */
421   crt_image_writefile,         /* write file */
422   crt_image_deletefile,         /* delete file */
423   crt_image_create,            /* create image */
424   NULL,                        /* read sector */
425   NULL,                        /* write sector */
426   c64crt_fileeopts,               /* file _options */
427   c64crt_createopts               /* create options */
428)
429
430static int crt_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
431{
432   crt_image *image;
433
434   image=*(crt_image**)outimg=(crt_image *) malloc(sizeof(crt_image));
435   if (!image) return IMGTOOLERR_OUTOFMEMORY;
436
437   memset(image, 0, sizeof(crt_image));
438   image->base.module = mod;
439   image->size=stream_size(f);
440   image->file_handle=f;
441
442   image->data = (unsigned char *) malloc(image->size);
443   if ( (!image->data)
444       ||(stream_read(f, image->data, image->size)!=image->size) ) {
445      free(image);
446      *outimg=NULL;
447      return IMGTOOLERR_OUTOFMEMORY;
448   }
449
450   return 0;
451}
452
453static void crt_image_exit(imgtool_image *img)
454{
455   crt_image *image=(crt_image*)img;
456   if (image->modified) {
457      stream_clear(image->file_handle);
458      stream_write(image->file_handle, image->data, image->size);
459   }
460   stream_close(image->file_handle);
461   free(image->data);
462   free(image);
463}
464
465static void crt_image_info(imgtool_image *img, char *string, const int len)
466{
467   crt_image *image=(crt_image*)img;
468   sprintf(string, "%-32s\nversion:%.4x type:%d:%s exrom:%d game:%d",
469         HEADER(image)->name,
470         GET_UWORD(HEADER(image)->version),
471         GET_UWORD(HEADER(image)->hardware_type),
472         hardware_types[GET_UWORD(HEADER(image)->hardware_type)],
473         HEADER(image)->exrom_line, HEADER(image)->game_line);
474   return;
475}
476
477static int crt_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
478{
479   crt_image *image=(crt_image*)img;
480   crt_iterator *iter;
481
482   iter=*(crt_iterator**)outenum = (crt_iterator *) malloc(sizeof(crt_iterator));
483   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
484
485   iter->base.module = img->module;
486
487   iter->image=image;
488   iter->pos = GET_ULONG( HEADER(image)->length );
489   iter->number = 0;
490   return 0;
491}
492
493static int crt_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
494{
495   crt_iterator *iter=(crt_iterator*)enumeration;
496
497   ent->corrupt=0;
498   
499   if (!(ent->eof=(iter->pos>=iter->image->size))) {
500      sprintf(ent->fname,"%d", iter->number);
501      ent->filesize=GET_UWORD( PACKET(iter->image, iter->pos)->length );
502      if (ent->attr) {
503          unsigned crc=crc32(0, iter->image->data+iter->pos+sizeof(crt_packet), ent->filesize);
504         sprintf(ent->attr,"%-4s %s bank:%-2d addr:%.4x crc:%8x",
505               (char*)PACKET(iter->image, iter->pos),
506               chip_types[GET_UWORD(PACKET(iter->image,iter->pos)->chip_type)],
507               GET_UWORD( PACKET(iter->image,iter->pos)->bank),
508               GET_UWORD( PACKET(iter->image,iter->pos)->address),
509            crc);
510      }
511      iter->number++;
512
513      iter->pos+=GET_ULONG( PACKET(iter->image, iter->pos)->packet_length );
514   }
515   return 0;
516}
517
518static void crt_image_closeenum(imgtool_directory *enumeration)
519{
520   free(enumeration);
521}
522
523#if 0
524static size_t crt_image_freespace(imgtool_image *img)
525{
526   int i;
527   rsdos_diskimage *rsimg = (rsdos_diskimage *) img;
528   size_t s = 0;
529
530   for (i = 0; i < GRANULE_COUNT; i++)
531      if (rsimg->granulemap[i] == 0xff)
532         s += (9 * 256);
533   return s;
534}
535#endif
536
537static int crt_image_findfile(crt_image *image, const char *fname)
538{
539   int nr=0;
540   char name[6];
541   int i=sizeof(crt_header);
542
543   while (i<image->size) {
544      sprintf(name, "%d",nr);
545      if (!strcmp(fname, name) ) return i;
546      i+=GET_ULONG( PACKET(image, i)->packet_length );
547      nr++;
548   }
549   return 0;
550}
551
552static int crt_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
553{
554   crt_image *image=(crt_image*)img;
555   int size;
556   int pos;
557
558   if (!(pos=crt_image_findfile(image, fname)) )
559      return IMGTOOLERR_MODULENOTFOUND;
560
561   size=GET_UWORD( PACKET(image, pos)->length );
562   if (stream_write(destf, image->data+pos+sizeof(crt_packet), size)!=size) {
563      return IMGTOOLERR_WRITEERROR;
564   }
565
566   return 0;
567}
568
569static int crt_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef,
570                        const ResolvedOption *_options)
571{
572   crt_image *image=(crt_image*)img;
573   int size;
574   int pos;
575
576   size=stream_size(sourcef);
577   if (!(pos=crt_image_findfile(image, fname)) ) {
578      // appending
579      pos=image->size;
580      if (!(image->data=realloc(image->data, image->size+size+sizeof(crt_packet))) )
581         return IMGTOOLERR_OUTOFMEMORY;
582      image->size+=size+sizeof(crt_packet);
583   } else {
584      int oldsize=GET_ULONG(PACKET(image,pos)->packet_length);
585      // overwritting
586      if (!(image->data=realloc(image->data, image->size+size+sizeof(crt_packet)-oldsize) ) )
587         return IMGTOOLERR_OUTOFMEMORY;
588      if (image->size-pos-oldsize!=0) {
589         memmove(image->data+pos+size+sizeof(crt_packet), image->data+pos+oldsize,
590               image->size-pos-oldsize);
591      }
592      image->size+=size+sizeof(crt_packet)-oldsize;
593   }
594   if (stream_read(sourcef, image->data+pos+sizeof(crt_packet), size)!=size) {
595      return IMGTOOLERR_READERROR;
596   }
597   memset(image->data+pos, 0, sizeof(crt_packet));
598   memcpy(PACKET(image,pos)->id,"CHIP",4);
599   SET_ULONG( PACKET(image, pos)->packet_length, size+sizeof(crt_packet));
600   SET_UWORD(PACKET(image, pos)->chip_type, _options[C64CRT_FILEOPTION_FTYPE].i);
601   SET_UWORD( PACKET(image, pos)->address, _options[C64CRT_FILEOPTION_FADDR].i);
602   SET_UWORD( PACKET(image, pos)->bank, _options[C64CRT_FILEOPTION_FBANK].i);
603   SET_UWORD( PACKET(image, pos)->length, size);
604
605   image->modified=1;
606
607   return 0;
608}
609
610static int crt_image_deletefile(imgtool_image *img, const char *fname)
611{
612   crt_image *image=(crt_image*)img;
613   int size;
614   int pos;
615
616   if (!(pos=crt_image_findfile(image, fname)) ) {
617      return IMGTOOLERR_MODULENOTFOUND;
618   }
619   size=GET_ULONG(PACKET(image, pos)->packet_length);
620   if (image->size-pos-size>0)
621      memmove(image->data+pos, image->data+pos+size, image->size-pos-size);
622   image->size-=size;
623   image->modified=1;
624
625   return 0;
626}
627
628static int crt_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *_options)
629{
630   crt_header header={ "C64 CARTRIDGE   " };
631   SET_ULONG(header.length, sizeof(header));
632   SET_UWORD(header.version, 0x100);
633   SET_UWORD(header.hardware_type, _options[C64CRT_CREATEOPTION_HARDWARETYPE].i);
634   header.game_line=_options[C64CRT_CREATEOPTION_GAMELINE].i;
635   header.exrom_line=_options[C64CRT_CREATEOPTION_EXROMLINE].i;
636   if (_options[C64CRT_CREATEOPTION_LABEL].s) strcpy(header.name, _options[C64CRT_CREATEOPTION_LABEL].s);
637   return (stream_write(f, &header, sizeof(crt_header)) == sizeof(crt_header))
638      ? 0 : IMGTOOLERR_WRITEERROR;
639}
640
src/mess/tools/imgtool/modules/macbin.c
r0r1340
1/****************************************************************************
2
3   macbin.c
4
5   MacBinary filter for use with Mac and ProDOS drivers
6
7*****************************************************************************
8
9  MacBinary file format
10
11  Offset  Length  Description
12  ------  ------  -----------
13       0       1  [I]   Magic byte (0x00)
14      1      64  [I]   File name (Pascal String)
15      65       4  [I]   File Type Code
16     69       4  [I]   File Creator Code
17     73       1  [I]   Finder Flags (bits 15-8)
18     74       1  [I]   Magic byte (0x00)
19     75       2  [I]   File Vertical Position
20     77       2  [I]   File Horizontal Position
21     79       2  [I]   Window/Folder ID
22     81       1  [I]   Protected (bit 0)
23     82       1  [I]   Magic byte (0x00)
24     83       4  [I]   Data Fork Length
25     87       4  [I]   Resource Fork Length
26     91       4  [I]   Creation Date
27     95       4  [I]   Last Modified Date
28     99       2  [I]   "Get Info" comment length
29     101       1  [II]  Finder Flags (bits 7-0)
30    102       4  [III] MacBinary III Signature 'mBIN'
31    106       1  [III] Script of Filename
32    107       1  [III] Extended Finder Flags
33    116       4  [II]  Unpacked Length
34    120       2  [II]  Secondary Header Length
35    122       1  [II]  MacBinary II Version Number (II: 0x81, III: 0x82)
36    123       1  [II]  Minimum Compatible MacBinary II Version Number (0x81)
37    124       2  [II]  CRC of previous 124 bytes 
38   
39   For more information, consult http://www.lazerware.com/formats/macbinary.html
40
41   TODO: I believe that the script code is some sort of identifier identifying
42   the character set used for the filename.  If this is true, we are not
43   handling that properly
44
45*****************************************************************************/
46
47#include <string.h>
48
49#include "imgtool.h"
50#include "macutil.h"
51
52
53
54static UINT32 pad128(UINT32 length)
55{
56   if (length % 128)
57      length += 128 - (length % 128);
58   return length;
59}
60
61
62
63static imgtoolerr_t macbinary_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
64{
65   static const UINT32 attrs[] =
66   {
67      IMGTOOLATTR_TIME_CREATED,
68      IMGTOOLATTR_TIME_LASTMODIFIED,
69      IMGTOOLATTR_INT_MAC_TYPE,
70      IMGTOOLATTR_INT_MAC_CREATOR,
71      IMGTOOLATTR_INT_MAC_FINDERFLAGS,
72      IMGTOOLATTR_INT_MAC_COORDX,
73      IMGTOOLATTR_INT_MAC_COORDY,
74      IMGTOOLATTR_INT_MAC_FINDERFOLDER,
75      IMGTOOLATTR_INT_MAC_SCRIPTCODE,
76      IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS,
77      0
78   };
79   imgtoolerr_t err;
80   UINT8 header[128];
81   const char *basename;
82   int i;
83
84   UINT32 type_code = 0x3F3F3F3F;
85   UINT32 creator_code = 0x3F3F3F3F;
86   UINT16 finder_flags = 0;
87   UINT16 coord_x = 0;
88   UINT16 coord_y = 0;
89   UINT16 finder_folder = 0;
90   UINT8 script_code = 0;
91   UINT8 extended_flags = 0;
92
93   imgtool_forkent fork_entries[4];
94   const imgtool_forkent *data_fork = NULL;
95   const imgtool_forkent *resource_fork = NULL;
96   UINT32 creation_time = 0;
97   UINT32 lastmodified_time = 0;
98   imgtool_attribute attr_values[10];
99
100   /* get the forks */
101   err = imgtool_partition_list_file_forks(partition, filename, fork_entries, sizeof(fork_entries));
102   if (err)
103      return err;
104   for (i = 0; fork_entries[i].type != FORK_END; i++)
105   {
106      if (fork_entries[i].type == FORK_DATA)
107         data_fork = &fork_entries[i];
108      else if (fork_entries[i].type == FORK_RESOURCE)
109         resource_fork = &fork_entries[i];
110   }
111
112   /* get the attributes */
113   err = imgtool_partition_get_file_attributes(partition, filename, attrs, attr_values);
114   if (err && (ERRORCODE(err) != IMGTOOLERR_UNIMPLEMENTED))
115      return err;
116   if (err == IMGTOOLERR_SUCCESS)
117   {
118      creation_time     = mac_setup_time(attr_values[0].t);
119      lastmodified_time = mac_setup_time(attr_values[1].t);
120      type_code         = attr_values[2].i;
121      creator_code      = attr_values[3].i;
122      finder_flags      = attr_values[4].i;
123      coord_x           = attr_values[5].i;
124      coord_y           = attr_values[6].i;
125      finder_folder     = attr_values[7].i;
126      script_code       = attr_values[8].i;
127      extended_flags    = attr_values[9].i;
128   }
129
130   memset(header, 0, sizeof(header));
131
132   /* place filename */
133   basename = filename;
134   while(basename[strlen(basename) + 1])
135      basename += strlen(basename) + 1;
136   pascal_from_c_string((unsigned char *) &header[1], 64, basename);
137
138   place_integer_be(header,  65, 4, type_code);
139   place_integer_be(header,  69, 4, creator_code);
140   place_integer_be(header,  73, 1, (finder_flags >> 8) & 0xFF);
141   place_integer_be(header,  75, 2, coord_x);
142   place_integer_be(header,  77, 2, coord_y);
143   place_integer_be(header,  79, 2, finder_folder);
144   place_integer_be(header,  83, 4, data_fork ? data_fork->size : 0);
145   place_integer_be(header,  87, 4, resource_fork ? resource_fork->size : 0);
146   place_integer_be(header,  91, 4, creation_time);
147   place_integer_be(header,  95, 4, lastmodified_time);
148   place_integer_be(header, 101, 1, (finder_flags >> 0) & 0xFF);
149   place_integer_be(header, 102, 4, 0x6D42494E);
150   place_integer_be(header, 106, 1, script_code);
151   place_integer_be(header, 107, 1, extended_flags);
152   place_integer_be(header, 122, 1, 0x82);
153   place_integer_be(header, 123, 1, 0x81);
154   place_integer_be(header, 124, 2, ccitt_crc16(0, header, 124));
155
156   stream_write(destf, header, sizeof(header));
157   
158   if (data_fork)
159   {
160      err = imgtool_partition_read_file(partition, filename, "", destf, NULL);
161      if (err)
162         return err;
163
164      stream_fill(destf, 0, pad128(data_fork->size));
165   }
166   
167   if (resource_fork)
168   {
169      err = imgtool_partition_read_file(partition, filename, "RESOURCE_FORK", destf, NULL);
170      if (err)
171         return err;
172
173      stream_fill(destf, 0, pad128(resource_fork->size));
174   }
175
176   return IMGTOOLERR_SUCCESS;
177}
178
179
180
181static imgtoolerr_t write_fork(imgtool_partition *partition, const char *filename, const char *fork,
182   imgtool_stream *sourcef, UINT64 pos, UINT64 fork_len, option_resolution *opts)
183{
184   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
185   imgtool_stream *mem_stream = NULL;
186   size_t len;
187
188   if (fork_len > 0)
189   {
190      mem_stream = stream_open_mem(NULL, 0);
191      if (!mem_stream)
192      {
193         err = IMGTOOLERR_OUTOFMEMORY;
194         goto done;
195      }
196
197      stream_seek(sourcef, pos, SEEK_SET);
198      len = stream_transfer(mem_stream, sourcef, fork_len);
199      if (len < fork_len)
200         stream_fill(mem_stream, 0, fork_len);
201
202      stream_seek(mem_stream, 0, SEEK_SET);
203      err = imgtool_partition_write_file(partition, filename, fork, mem_stream, opts, NULL);
204      if (err)
205         goto done;
206   }
207
208done:
209   if (mem_stream)
210      stream_close(mem_stream);
211   return err;
212}
213
214
215
216static imgtoolerr_t macbinary_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *opts)
217{
218   static const UINT32 attrs[] =
219   {
220      IMGTOOLATTR_TIME_CREATED,
221      IMGTOOLATTR_TIME_LASTMODIFIED,
222      IMGTOOLATTR_INT_MAC_TYPE,
223      IMGTOOLATTR_INT_MAC_CREATOR,
224      IMGTOOLATTR_INT_MAC_FINDERFLAGS,
225      IMGTOOLATTR_INT_MAC_COORDX,
226      IMGTOOLATTR_INT_MAC_COORDY,
227      IMGTOOLATTR_INT_MAC_FINDERFOLDER,
228      IMGTOOLATTR_INT_MAC_SCRIPTCODE,
229      IMGTOOLATTR_INT_MAC_EXTENDEDFLAGS,
230      0
231   };
232   imgtoolerr_t err;
233   imgtool_image *image = imgtool_partition_image(partition);
234   UINT8 header[128];
235   UINT32 datafork_size;
236   UINT32 resourcefork_size;
237   UINT64 total_size;
238   UINT32 creation_time;
239   UINT32 lastmodified_time;
240   int version;
241   imgtool_attribute attr_values[10];
242
243   UINT32 type_code;
244   UINT32 creator_code;
245   UINT16 finder_flags;
246   UINT16 coord_x;
247   UINT16 coord_y;
248   UINT16 finder_folder;
249   UINT8 script_code = 0;
250   UINT8 extended_flags = 0;
251
252   /* read in the header */
253   memset(header, 0, sizeof(header));
254   stream_read(sourcef, header, sizeof(header));
255
256   /* check magic and zero fill bytes */
257   if (header[0] != 0x00)
258      return IMGTOOLERR_CORRUPTFILE;
259   if (header[74] != 0x00)
260      return IMGTOOLERR_CORRUPTFILE;
261   if (header[82] != 0x00)
262      return IMGTOOLERR_CORRUPTFILE;
263
264   datafork_size = pick_integer_be(header, 83, 4);
265   resourcefork_size = pick_integer_be(header, 87, 4);
266   total_size = stream_size(sourcef);
267
268   /* size of a MacBinary header is always 128 bytes */
269   if (total_size - pad128(datafork_size) - pad128(resourcefork_size) != 128)
270      return IMGTOOLERR_CORRUPTFILE;
271
272   /* check filename length byte */
273   if ((header[1] <= 0x00) || (header[1] > 0x3F))
274      return IMGTOOLERR_CORRUPTFILE;
275
276   /* check the CRC */
277   if (pick_integer_be(header, 124, 2) != ccitt_crc16(0, header, 124))
278   {
279      /* the CRC does not match; this file is MacBinary I */
280      version = 1;
281   }
282   else if (pick_integer_be(header, 102, 4) != 0x6D42494E)
283   {
284      /* did not see 'mBIN'; this file is MacBinary II */
285      if (header[122] < 0x81)
286         return IMGTOOLERR_CORRUPTFILE;
287      if (header[123] < 0x81)
288         return IMGTOOLERR_CORRUPTFILE;
289      version = 2;
290   }
291   else
292   {
293      /* we did see 'mBIN'; this file is MacBinary III */
294      if (header[122] < 0x82)
295         return IMGTOOLERR_CORRUPTFILE;
296      if (header[123] < 0x81)
297         return IMGTOOLERR_CORRUPTFILE;
298      version = 3;
299   }
300
301   type_code         = pick_integer_be(header, 65, 4);
302   creator_code      = pick_integer_be(header, 69, 4);
303   finder_flags      = pick_integer_be(header, 73, 1) << 8;
304   coord_x           = pick_integer_be(header, 75, 2);
305   coord_y           = pick_integer_be(header, 77, 2);
306   finder_folder     = pick_integer_be(header, 79, 2);
307   creation_time     = pick_integer_be(header, 91, 4);
308   lastmodified_time = pick_integer_be(header, 95, 4);
309
310   if (image)
311   {
312      /* write out both forks */
313      err = write_fork(partition, filename, "", sourcef, sizeof(header), datafork_size, opts);
314      if (err)
315         return err;
316      err = write_fork(partition, filename, "RESOURCE_FORK", sourcef, sizeof(header) + pad128(datafork_size), resourcefork_size, opts);
317      if (err)
318         return err;
319
320      /* set up attributes */
321      attr_values[0].t = mac_crack_time(creation_time);
322      attr_values[1].t = mac_crack_time(lastmodified_time);
323      attr_values[2].i = type_code;
324      attr_values[3].i = creator_code;
325      attr_values[4].i = finder_flags;
326      attr_values[5].i = coord_x;
327      attr_values[6].i = coord_y;
328      attr_values[7].i = finder_folder;
329      attr_values[8].i = script_code;
330      attr_values[9].i = extended_flags;
331
332      err = imgtool_partition_put_file_attributes(partition, filename, attrs, attr_values);
333      if (err)
334         return err;
335   }
336
337   return IMGTOOLERR_SUCCESS;
338}
339
340
341
342static imgtoolerr_t macbinary_checkstream(imgtool_stream *stream, imgtool_suggestion_viability_t *viability)
343{
344   imgtoolerr_t err;
345
346   err = macbinary_writefile(NULL, NULL, NULL, stream, NULL);
347   if (err == IMGTOOLERR_CORRUPTFILE)
348   {
349      /* the filter returned corrupt; this is not a valid file */
350      *viability = SUGGESTION_END;
351      err = IMGTOOLERR_SUCCESS;
352   }
353   else if (err == IMGTOOLERR_SUCCESS)
354   {
355      /* success; lets recommend this filter */
356      *viability = SUGGESTION_RECOMMENDED;
357   }
358   return err;
359}
360
361
362
363void filter_macbinary_getinfo(UINT32 state, union filterinfo *info)
364{
365   switch(state)
366   {
367      case FILTINFO_STR_NAME:         info->s = "macbinary"; break;
368      case FILTINFO_STR_HUMANNAME:   info->s = "MacBinary"; break;
369      case FILTINFO_STR_EXTENSION:   info->s = "bin"; break;
370      case FILTINFO_PTR_READFILE:      info->read_file = macbinary_readfile; break;
371      case FILTINFO_PTR_WRITEFILE:   info->write_file = macbinary_writefile; break;
372      case FILTINFO_PTR_CHECKSTREAM:   info->check_stream = macbinary_checkstream; break;
373   }
374}
src/mess/tools/imgtool/modules/ti85.c
r0r1340
1#include "osdepend.h"
2#include "imgtoolx.h"
3#include "utils.h"
4#include "formats/ti85_ser.h"
5
6static const char *var_type[] = {
7      "Real number",         //0x00
8      "Complex number",      //0x01
9      "Real vector",         //0x02
10      "Complex vector",      //0x03
11      "Real list",         //0x04
12      "Complex list",         //0x05
13      "Real matrix",         //0x06
14      "Complex matrix",      //0x07
15      "Real constatnt",      //0x08
16      "Complex constant",      //0x09
17      "Equation",         //0x0a
18      "Range settings",      //0x0b
19      "String",         //0x0c
20      "Graphics database",      //0x0d
21      "Graphics database",      //0x0e
22      "Graphics database",      //0x0f
23      "Graphics database",      //0x10
24      "Picture",         //0x11
25      "Program",         //0x12
26      "Range settings",      //0x13
27      "Unknown",         //0x14
28      "Range settings",      //0x15
29      "Range settings",      //0x16
30      "Range settings",      //0x17
31      "Range settings",      //0x18
32      "Range settings",      //0x19
33      "Range settings",      //0x1a
34      "Range settings"};      //0x1b
35
36typedef struct {
37   char signature[0x08];
38   unsigned char marker[0x03];
39   char comment[0x2a];
40   unsigned char data_size[0x02];
41} ti85_header;
42
43typedef struct {
44   imgtool_image base;
45   imgtool_stream *file_handle;
46   unsigned int size;
47   int modified;
48   UINT8 *data;
49   ti85_entry * entries;
50   int number_of_entries;
51} ti85_file;
52
53typedef struct {
54   imgtool_image base;
55   imgtool_stream *file_handle;
56   unsigned int size;
57   int modified;
58   UINT8 *data;
59} ti85b_file;
60
61typedef struct {
62   imgtool_directory base;
63   ti85_file *image;
64   int index;
65} ti85_iterator;
66
67typedef struct {
68   imgtool_directory base;
69   ti85b_file *image;
70   int index;
71} ti85b_iterator;
72
73#define HEADER(file) ((ti85_header*)file->data)
74
75static struct OptionTemplate ti85_fileoptions[] =
76{
77   { "ftype", "File type", IMGOPTION_FLAG_TYPE_INTEGER | IMGOPTION_FLAG_HASDEFAULT,0,27,"12"},
78   { NULL, 0, 0, 0, 0 }
79};
80
81static struct OptionTemplate ti85_createoptions[] =
82{
83   { "comment", "Comment", IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,0,0,"TI-85 file created with ImgTool"},
84   { NULL, NULL, 0, 0, 0, 0 }
85};
86
87#define TI85_OPTION_FTYPE   0
88#define TI85_OPTION_COMMENT   0
89
90static void ti85_file_info(imgtool_image *img, char *string, const int len);
91static int ti85_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
92static void ti85_file_exit(imgtool_image *img);
93static int ti85_file_beginenum(imgtool_image *img, imgtool_directory **outenum);
94static int ti85_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
95static void ti85_file_closeenum(imgtool_directory *enumeration);
96static int ti85_file_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
97static int ti85_file_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
98static int ti85_file_deletefile(imgtool_image *img, const char *fname);
99static int ti85_file_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
100
101static void ti85b_file_info(imgtool_image *img, char *string, const int len);
102static int ti85b_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
103static void ti85b_file_exit(imgtool_image *img);
104static int ti85b_file_beginenum(imgtool_image *img, imgtool_directory **outenum);
105static int ti85b_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
106static void ti85b_file_closeenum(imgtool_directory *enumeration);
107
108
109#define TI85FILE(name,human_name,extension) \
110IMAGEMODULE(         \
111   name,         \
112   human_name,      \
113   extension,      \
114   NULL,         \
115   NULL,         \
116   NULL,         \
117   0,         \
118   ti85_file_init,      \
119   ti85_file_exit,      \
120   ti85_file_info,      \
121   ti85_file_beginenum,   \
122   ti85_file_nextenum,   \
123   ti85_file_closeenum,   \
124   NULL,         \
125   ti85_file_readfile,   \
126   ti85_file_writefile,   \
127   ti85_file_deletefile,   \
128   ti85_file_create,   \
129   NULL,         \
130   NULL,         \
131   ti85_fileoptions,   \
132   ti85_createoptions   \
133)
134
135TI85FILE (ti85p, "TI-85 program file", "85p")
136TI85FILE (ti85s, "TI-85 string file (also ZShell programs)", "85s")
137TI85FILE (ti85i, "TI-85 picture file (85-image)", "85i")
138TI85FILE (ti85n, "TI-85 real number file", "85n")
139TI85FILE (ti85c, "TI-85 complex number file", "85c")
140TI85FILE (ti85l, "TI-85 list (real or complex) file", "85l")
141TI85FILE (ti85k, "TI-85 constant file", "85k")
142TI85FILE (ti85m, "TI-85 matrix (real or complex) file", "85m")
143TI85FILE (ti85v, "TI-85 vector (real or complex) file", "85v")
144TI85FILE (ti85d, "TI-85 graphics database file", "85d")
145TI85FILE (ti85e, "TI-85 equation file", "85e")
146TI85FILE (ti85r, "TI-85 range settings file", "85r")
147TI85FILE (ti85g, "TI-85 grouped file", "85g")
148TI85FILE (ti85, "TI-85 file", "85?")
149TI85FILE (ti86p, "TI-86 program file", "86p")
150TI85FILE (ti86s, "TI-86 string file (also ZShell programs)", "86s")
151TI85FILE (ti86i, "TI-86 picture file (85-image)", "86i")
152TI85FILE (ti86n, "TI-86 real number file", "86n")
153TI85FILE (ti86c, "TI-86 complex number file", "86c")
154TI85FILE (ti86l, "TI-86 list (real or complex) file", "86l")
155TI85FILE (ti86k, "TI-86 constant file", "86k")
156TI85FILE (ti86m, "TI-86 matrix (real or complex) file", "86m")
157TI85FILE (ti86v, "TI-86 vector (real or complex) file", "86v")
158TI85FILE (ti86d, "TI-86 graphics database file", "86d")
159TI85FILE (ti86e, "TI-86 equation file", "86e")
160TI85FILE (ti86r, "TI-86 range settings file", "86r")
161TI85FILE (ti86g, "TI-86 grouped file", "86g")
162TI85FILE (ti86, "TI-86 file", "86?")
163
164
165IMAGEMODULE(
166   ti85b,
167   "TI-85 memory backup file",
168   "85b",
169   NULL,
170   NULL,
171   NULL,
172   0,
173   ti85b_file_init,
174   ti85b_file_exit,
175   ti85b_file_info,
176   ti85b_file_beginenum,
177   ti85b_file_nextenum,
178   ti85b_file_closeenum,
179   NULL,
180   NULL,
181   NULL,
182   NULL,
183   NULL,
184   NULL,
185   NULL,
186   NULL,
187   NULL
188)
189
190static int ti85_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
191{
192   ti85_file *file;
193
194   file=*(ti85_file**)outimg=(ti85_file *) malloc(sizeof(ti85_file));
195   if (!file) return IMGTOOLERR_OUTOFMEMORY;
196
197   file->base.module = mod;
198   file->size=stream_size(f);
199   file->file_handle=f;
200
201   file->data = (unsigned char *) malloc(file->size);
202   if (!file->data) return IMGTOOLERR_OUTOFMEMORY;
203
204   if (stream_read(f, file->data, file->size)!=file->size)
205   {
206      free(file);
207      *outimg=NULL;
208      return IMGTOOLERR_READERROR;
209   }
210
211   if ( strncmp((char *) file->data, (char *) ti85_file_signature, 11) &&
212             strncmp((char *) file->data, (char *) ti86_file_signature, 11) )
213   {
214      free(file);
215      return IMGTOOLERR_CORRUPTIMAGE;
216   }
217
218
219   if (file->data[0x3b]==0x1d)
220   {
221      free(file);
222      return IMGTOOLERR_CORRUPTIMAGE;
223   }
224
225   file->number_of_entries = ti85_variables_count(file->data, file->size);
226
227
228   file->entries = (ti85_entry*) malloc (file->number_of_entries*sizeof(ti85_entry));
229   if (!file->entries) return IMGTOOLERR_OUTOFMEMORY;
230
231
232   ti85_variables_read(file->data, file->size, file->entries);
233
234   return 0;
235}
236
237static void ti85_file_exit(imgtool_image * img)
238{
239   ti85_file *file=(ti85_file*)img;
240   if (file->modified) {
241      stream_clear(file->file_handle);
242      stream_write(file->file_handle, file->data, file->size);
243   }
244   stream_close(file->file_handle);
245   free(file->entries);
246   free(file->data);
247   free(file);
248}
249
250static void ti85_file_info(imgtool_image *img, char *string, const int len)
251{
252   UINT16 file_checksum;
253   UINT16 checksum;
254   unsigned int data_size;
255
256   ti85_file *file=(ti85_file*)img;
257   char comment_with_null[0x2a+1]={ 0 };
258
259   strncpy(comment_with_null, HEADER(file)->comment, 0x2a);
260
261   data_size = HEADER(file)->data_size[1]*256 + HEADER(file)->data_size[0];
262   file_checksum = file->data[file->size-1]*256+file->data[file->size-2];
263   checksum = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE);
264
265   sprintf(string,"\nComment   : %s\nData size : %04xh\nEntries   : %d\nChecksum  : %04xh",
266         comment_with_null,
267         data_size,
268         file->number_of_entries,
269         file_checksum);
270   if (checksum!=file_checksum) strcat (string, " (BAD)");
271}
272
273static int ti85_file_beginenum(imgtool_image *img, imgtool_directory **outenum)
274{
275   ti85_file *file=(ti85_file*)img;
276   ti85_iterator *iter;
277
278   iter=*(ti85_iterator**)outenum = (ti85_iterator *) malloc(sizeof(ti85_iterator));
279   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
280
281   iter->base.module = img->module;
282
283   iter->image=file;
284   iter->index = 0;
285   return 0;
286}
287
288static int ti85_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
289{
290   ti85_iterator *iter=(ti85_iterator*)enumeration;
291
292   ent->eof=iter->index>=iter->image->number_of_entries;
293   if (!ent->eof)
294   {
295      memset(ent->fname,0,iter->image->entries[iter->index].name_size+1);
296      strncpy (ent->fname,
297          (char*)iter->image->data+iter->image->entries[iter->index].offset+0x06,
298          iter->image->entries[iter->index].name_size);
299      if (ent->attr)
300         sprintf(ent->attr,"%s (%02xh)",
301            var_type[iter->image->entries[iter->index].type],
302            iter->image->entries[iter->index].type);
303      ent->filesize = iter->image->entries[iter->index].data_size;
304      ent->corrupt=0;
305      iter->index++;
306   }
307
308   return 0;
309}
310
311static void ti85_file_closeenum(imgtool_directory *enumeration)
312{
313   free(enumeration);
314}
315
316static int ti85_findfile (ti85_file * file, const char * fname)
317{
318   int i;
319
320   for (i = 0; i < file->number_of_entries; i++)
321      if (!strnicmp(fname, (char *) file->data+file->entries[i].offset+0x06, file->entries[i].name_size) )
322         return i;     
323
324   return -1;
325}
326
327
328static int ti85_file_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
329{
330   ti85_file *file=(ti85_file*)img;
331   int start, size;
332   int ind;
333
334   if ((ind=ti85_findfile(file, fname))==-1) return IMGTOOLERR_MODULENOTFOUND;
335
336   size = file->entries[ind].data_size;
337   start = file->entries[ind].offset+file->entries[ind].head_size+0x04;
338
339   if (stream_write(destf, file->data+start, size) != size)
340              return IMGTOOLERR_WRITEERROR;
341   return 0;
342}
343
344static int ti85_file_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_)
345{
346   ti85_file *file=(ti85_file*)img;
347   int ind;
348
349   unsigned char name_size = strlen (fname);
350   UINT16 head_size = 0x04 + name_size;
351   UINT16 data_size = stream_size(sourcef);
352   unsigned char type = options_[TI85_OPTION_FTYPE].i;
353   unsigned int offset = file->size-2;
354
355   if (!(file->data=realloc(file->data, file->size+data_size+head_size+4)) )
356      return IMGTOOLERR_OUTOFMEMORY;
357
358   file->size+=data_size+head_size+4;
359
360   if (!(file->entries=realloc(file->entries, sizeof(ti85_entry)*(file->number_of_entries+1))) )
361      return IMGTOOLERR_OUTOFMEMORY;
362   file->number_of_entries++;
363
364   ind = file->number_of_entries-1;
365
366   file->entries[ind].head_size = head_size;
367   file->entries[ind].data_size = data_size;
368   file->entries[ind].type = type;
369   file->entries[ind].name_size = name_size;
370   file->entries[ind].offset = offset;
371
372   HEADER(file)->data_size[0] = (file->size-0x36)&0x00ff;
373   HEADER(file)->data_size[1] = ((file->size-0x36)&0xff00)>>8;
374
375   file->data[offset] = head_size&0x00ff;
376   file->data[offset+0x01] = (head_size&0xff00)>>8;
377   file->data[offset+0x02] = data_size&0x00ff;
378   file->data[offset+0x03] = (data_size&0xff00)>>8;
379   file->data[offset+0x04] = type;
380   file->data[offset+0x05] = name_size;
381
382   strncpy ((char*) file->data+offset+0x06, fname, name_size);
383
384   file->data[offset+head_size+0x02] = data_size%0x00ff;
385   file->data[offset+head_size+0x03] = (data_size%0xff00)>>8;
386
387   if (stream_read(sourcef, file->data+offset+head_size+0x04, data_size)!=data_size)
388      return IMGTOOLERR_READERROR;
389   
390   file->data[file->size-2] = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0x00ff;
391   file->data[file->size-1] = (ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0xff00)>>8;
392
393   file->modified=1;
394
395   return 0;
396}
397
398static int ti85_file_deletefile(imgtool_image *img, const char *fname)
399{
400   ti85_file *file=(ti85_file*)img;
401   int ind,i;
402   int size, start;
403
404   if ((ind=ti85_findfile(file, fname))==-1 )
405      return IMGTOOLERR_MODULENOTFOUND;
406
407   size = file->entries[ind].data_size+file->entries[ind].head_size+0x04;
408   start = file->entries[ind].offset;
409
410   memmove(file->data+start, file->data+start+size, file->size-start-size);
411   memmove(file->entries+ind*sizeof(ti85_entry),
412      file->entries+(ind+1)*sizeof(ti85_entry),
413      (file->number_of_entries-ind)*sizeof(ti85_entry));
414
415   for (i = ind; i < file->number_of_entries; i++)
416      file->entries[i].offset-=size;
417
418   file->size-=size;
419   file->data[file->size-2] = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0x00ff;
420   file->data[file->size-1] = (ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE)&0xff00)>>8;
421   file->modified=1;
422
423   return 0;
424}
425
426static int ti85_file_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
427{
428
429   ti85_header header = {   {'*','*','T','I','8','5','*','*'},
430            {0x1a, 0x0c, 0x00},
431            "",
432            {0x00, 0x00} };
433
434   char checksum[] = {0x00, 0x00};
435
436   strncpy(header.comment, options_[TI85_OPTION_COMMENT].s,0x2a);
437   if (stream_write(f, &header, sizeof(ti85_header)) != sizeof(ti85_header))
438      return  IMGTOOLERR_WRITEERROR;
439   if (stream_write(f, &checksum, 2) != 2)
440      return  IMGTOOLERR_WRITEERROR;
441
442   return 0;
443}
444
445static int ti85b_file_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
446{
447   ti85b_file *file;
448
449   file=*(ti85b_file**)outimg=(ti85b_file *) malloc(sizeof(ti85b_file));
450   if (!file) return IMGTOOLERR_OUTOFMEMORY;
451
452   file->base.module = mod;
453   file->size=stream_size(f);
454   file->file_handle=f;
455
456   file->data = (unsigned char *) malloc(file->size);
457   if (!file->data) return IMGTOOLERR_OUTOFMEMORY;
458
459   if (stream_read(f, file->data, file->size)!=file->size)
460   {
461      free(file);
462      *outimg=NULL;
463      return IMGTOOLERR_READERROR;
464   }
465
466   if ( strncmp((char *) file->data, (char *) ti85_file_signature, 11))
467   {
468      free(file);
469      return IMGTOOLERR_CORRUPTIMAGE;
470   }
471
472   if (file->data[0x3b]!=0x1d)
473   {
474      free(file);
475      return IMGTOOLERR_CORRUPTIMAGE;
476   }
477
478   return 0;
479}
480
481static void ti85b_file_exit(imgtool_image * img)
482{
483   ti85b_file *file=(ti85b_file*)img;
484   stream_close(file->file_handle);
485   free(file->data);
486   free(file);
487}
488
489static void ti85b_file_info(imgtool_image *img, char *string, const int len)
490{
491   UINT16 file_checksum;
492   UINT16 checksum;
493   unsigned int data_size;
494
495   ti85b_file *file=(ti85b_file*)img;
496   char comment_with_null[0x2a+1]={ 0 };
497
498   strncpy(comment_with_null, HEADER(file)->comment, 0x2a);
499
500   data_size = HEADER(file)->data_size[1]*256 + HEADER(file)->data_size[0] - 17;
501   file_checksum = file->data[file->size-1]*256+file->data[file->size-2];
502   checksum = ti85_calculate_checksum(file->data+TI85_HEADER_SIZE, file->size-2-TI85_HEADER_SIZE);
503
504   sprintf(string,"\nComment   : %s\nData size : %04xh\nChecksum  : %04xh",
505         comment_with_null,
506         data_size,
507         file_checksum);
508   if (checksum!=file_checksum) strcat (string, " (BAD)");
509}
510
511static int ti85b_file_beginenum(imgtool_image *img, imgtool_directory **outenum)
512{
513   ti85b_file *file=(ti85b_file*)img;
514   ti85b_iterator *iter;
515
516   iter=*(ti85b_iterator**)outenum = (ti85b_iterator *) malloc(sizeof(ti85b_iterator));
517   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
518
519   iter->base.module = img->module;
520
521   iter->image=file;
522   iter->index = 0;
523   return 0;
524}
525
526static int ti85b_file_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
527{
528   ti85b_iterator *iter=(ti85b_iterator*)enumeration;
529
530   ent->eof=iter->index>=3;
531   if (!ent->eof)
532   {
533      switch (iter->index) {
534         case 0 :
535            strcpy (ent->fname, "TI-85 Memory");
536            ent->filesize = iter->image->data[0x3a]*256 +iter->image->data[0x39];
537            break;
538         case 1 :
539            strcpy (ent->fname, "User Memory");
540            ent->filesize = iter->image->data[0x3d]*256 +iter->image->data[0x3c];
541            break;
542         case 2 :
543            strcpy (ent->fname, "VAT");
544            ent->filesize = iter->image->data[0x3f]*256 +iter->image->data[0x3e];
545            break;
546      }
547
548     
549      ent->corrupt=0;
550      iter->index++;
551   }
552
553   return 0;
554}
555
556static void ti85b_file_closeenum(imgtool_directory *enumeration)
557{
558   free(enumeration);
559}
src/mess/tools/imgtool/modules/nccard.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include <ctype.h>
5#include "osdepend.h"
6#include "imgtoolx.h"
7
8/* NC Card image handling code by Kevin Thacker. February 2001 */
9
10static int nc_card_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
11static void nc_card_image_exit(imgtool_image *img);
12static size_t nc_card_image_freespace(imgtool_image *img);
13static int nc_card_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
14static int nc_card_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
15static int nc_card_image_deletefile(imgtool_image *img, const char *fname);
16static int nc_card_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
17static int nc_card_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
18static int nc_card_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
19static void nc_card_image_closeenum(imgtool_directory *enumeration);
20
21IMAGEMODULE(
22   nccard,
23   "NC100/200 PCMCIA Ram Card Image",         /* human readable name */
24   "crd",                     /* file extension */
25   NULL,                     /* crcfile */
26   NULL,                     /* crc system name */
27   EOLN_CRLF,                  /* eoln */
28   IMGMODULE_FLAG_FILENAMES_PREFERUCASE,   /* flags */
29   nc_card_image_init,            /* init function */
30   nc_card_image_exit,            /* exit function */
31   NULL,                     /* info function */
32   nc_card_image_beginenum,      /* begin enumeration */
33   nc_card_image_nextenum,         /* enumerate next */
34   nc_card_image_closeenum,      /* close enumeration */
35   nc_card_image_freespace,      /* free space on image    */
36   nc_card_image_readfile,         /* read file */
37   nc_card_image_writefile,      /* write file */
38   nc_card_image_deletefile,      /* delete file */
39   nc_card_image_create,         /* create image */
40   NULL,
41   NULL,
42   NULL,                     /* file options */
43   NULL                     /* create options */
44)
45
46/*
47   NC PCMCIA RAM Card uses a FAT-like filesystem
48
49   Blocks are fixed at 256 bytes in size.
50   
51   Block 0 and Block 1 are reserved for a boot program.
52
53   Block 2 is reserved for root directory.
54
55   Block 3..(3+num_fat_blocks-1) are reserved for fat table.
56
57   Block (3+num_fat_blocks).. are used for data storage.
58
59   The FAT table uses two bytes for each entry.
60
61   The blocks used by a file are stored in the table in a link-list
62   structure.
63
64   The index of the first block is stored in the directory entry.
65   This entry is looked up in the FAT table. If the entry contains
66   another number (other than 0x0ffff and 0x0fffe), this is the next
67   block used by the file. If the number is 0x0ffff this means this
68   block is the last used by the file.
69   
70   0x0fffe indicates a reserved block.
71
72   The maximum supported PCMCIA Ram card size is 1mb, and there are
73   4096 256-byte blocks on each card. Therefore a FAT entry uses 12-bits
74   to store the block index, leaving the top 4-bits as a status??
75   
76   Maximum size of a file on the PCMCIA Ram card is 65536 bytes.
77*/
78struct nc_card_dir_entry
79{
80   /* filename, up to 12 chars, any unused chars are padded with zero's */
81   /* if first char is 0, this entry has been deleted */
82   unsigned char filename[12];
83   /* unused?? */
84   unsigned char unused[1];
85   /* 5 = basic, 0 = ascii text, 3=directory entry? */
86   unsigned char type;
87   /* size of file in bytes */
88   unsigned char size_low_byte;
89   unsigned char size_high_byte;
90   /* format unknown */
91   unsigned char packed_date[4];
92   /* 2-byte block index. first block used by file, other blocks
93   found in fat table */
94   unsigned char first_block_low;
95   unsigned char first_block_high;
96   /* unused?? */
97   unsigned char pad[32 - 22];
98};
99
100#define NC_FAT_END_OF_LIST   0x0ffff
101#define NC_FAT_RESERVED      0x0fffe
102
103struct nc_memcard
104{
105   unsigned char *memcard_data;
106   unsigned long memcard_size;
107   int fat_num_blocks;
108   int max_block_index;
109};
110
111/* each block is 256 bytes in size */
112#define NC_BLOCK_SIZE   256
113/* fat begins at block 3 */
114#define NC_FAT_BLOCK 3
115
116#define NC_DIR_ENTRY_TYPE_ASCII_FILE 0
117#define NC_DIR_ENTRY_TYPE_BASIC_FILE 5
118#define NC_DIR_ENTRY_TYPE_DIR 3
119
120
121static int   memcard_init(struct nc_memcard *memcard, int size)
122{
123   /* set size of memcard */
124   memcard->memcard_size = size;
125   /* allocate memory for it */
126   memcard->memcard_data = malloc(size);
127
128   if (memcard->memcard_data==0)
129      return 0;
130
131   /* calculate maximum number of blocks for fat to use */
132   memcard->max_block_index = (memcard->memcard_size + NC_BLOCK_SIZE-1)/NC_BLOCK_SIZE;
133
134   memcard->fat_num_blocks = ((memcard->max_block_index<<1) + NC_BLOCK_SIZE-1)/NC_BLOCK_SIZE;
135
136   return 1;
137}
138
139static void   memcard_free(struct nc_memcard *memcard)
140{
141   if (memcard->memcard_data!=NULL)
142   {
143      free(memcard->memcard_data);
144      memcard->memcard_data = NULL;
145   }
146}
147
148
149/* write to fat */
150static void   memcard_fat_write(struct nc_memcard *memcard,int index1, int data)
151{
152   unsigned long offset;
153
154   offset = (NC_FAT_BLOCK*NC_BLOCK_SIZE) + (index1<<1);
155
156   memcard->memcard_data[offset] = data & 0x0ff;
157   memcard->memcard_data[offset+1] = (data>>8);
158}
159
160/* read from fat */
161static int   memcard_fat_read(struct nc_memcard *memcard,int index1)
162{
163   int data;
164   unsigned long offset;
165
166   offset = (NC_FAT_BLOCK*NC_BLOCK_SIZE) + (index1<<1);
167
168   data = (memcard->memcard_data[offset] & 0x0ff) | ((memcard->memcard_data[offset+1] & 0x0ff)<<8);
169
170   return data;
171}
172
173/* get block index stored at the specified block index */
174static int memcard_fat_get_next_block(struct nc_memcard *memcard,int index1)
175{
176   return memcard_fat_read(memcard,index1);
177}
178
179/* get index of free block */
180static int   memcard_fat_get_free_block(struct nc_memcard *memcard)
181{
182   int i;
183
184   for (i=0; i<memcard->max_block_index; i++)
185   {
186      if (memcard_fat_read(memcard,i)==0)
187      {
188         return i;
189      }
190   }
191   return -1;
192}
193
194
195static unsigned long memcard_block_to_offset(int block)
196{
197   return block*NC_BLOCK_SIZE;
198}
199
200
201/* returns offset to directory entry */
202static unsigned long memcard_get_free_dir_entry(struct nc_memcard *memcard)
203{
204   /* offset within memcard data of this directory entry inside the parent */
205   int offset_in_parent_dir = NC_BLOCK_SIZE*2;
206   int previous_block;
207   int current_block = 2;
208   unsigned long offset;
209
210   while (current_block!=NC_FAT_END_OF_LIST)
211   {
212      int i;
213      offset = memcard_block_to_offset(current_block);
214
215      for (i=0; i<(NC_BLOCK_SIZE/32); i++)
216      {
217         if (memcard->memcard_data[offset]==0)
218         {
219            return offset;
220         }
221     
222         offset+=32;
223      }
224
225      previous_block = current_block;
226      current_block = memcard_fat_get_next_block(memcard,current_block);
227     
228      if (current_block!=NC_FAT_END_OF_LIST)
229      {
230         current_block &= 0x0fff;
231      }
232   }
233
234   /* out of entries within current blocks occupied by directory.
235   try to expand directory by one more block */
236
237   current_block = memcard_fat_get_free_block(memcard);
238
239   if (current_block!=-1)
240   {
241      int size;
242      unsigned long block_offset;
243      struct nc_card_dir_entry *dir_entry;
244
245      /* update size of directory */
246      dir_entry = (struct nc_card_dir_entry *)&memcard->memcard_data[offset_in_parent_dir];
247
248      /* get size of file from directory entry */
249      size = ((dir_entry->size_high_byte & 0x0ff)<<8) | (dir_entry->size_low_byte & 0x0ff);
250
251      size+=NC_BLOCK_SIZE;
252
253      /* set size of file in directory entry */
254      dir_entry->size_high_byte = (size>>8) & 0x0ff;
255      dir_entry->size_low_byte = size & 0x0ff;
256
257      /* got a new block */
258      block_offset = memcard_block_to_offset(current_block);
259
260      /* clear block */
261      /* only really necessary to clear first byte of each dir entry - but I'll clear
262      it all to give decent compressable cards */
263      memset(&memcard->memcard_data[block_offset], 0, NC_BLOCK_SIZE);
264
265      /* setup fat */
266      memcard_fat_write(memcard,previous_block, current_block|0x02000);
267      memcard_fat_write(memcard,current_block, NC_FAT_END_OF_LIST);
268
269      /* return first offset in new block */
270      return block_offset;
271   }
272
273   return -1;
274}
275
276const char *nc_memcard_executable_id = "NC100PRG";
277
278/* if memory card has "NC100PRG" at 0x0200 then the card is executable! */
279static int memcard_is_executable(struct nc_memcard *memcard)
280{
281   if (memcmp(&memcard->memcard_data[0x0200], nc_memcard_executable_id, 8)==0)
282   {
283      return 1;
284   }
285
286   return 0;
287}
288
289
290/* format a blank card */
291static void   memcard_format(struct nc_memcard *memcard)
292{
293   int i;
294
295   /* initialise all to zero */
296   /* real NC100 does not do this */
297   memset(memcard->memcard_data, 0, memcard->memcard_size);
298
299   /* not executable */
300   /* real NC100 does not do this */
301   memcard->memcard_data[0] = 0x0c9;
302
303   /* mark boot block as used */
304   memcard_fat_write(memcard,0, NC_FAT_END_OF_LIST);
305   memcard_fat_write(memcard,1, NC_FAT_END_OF_LIST);
306   /* mark directory block as used */
307   memcard_fat_write(memcard,2, NC_FAT_END_OF_LIST);
308
309   /* mark fat blocks as used */
310   for (i=0; i<memcard->fat_num_blocks; i++)
311   {
312      memcard_fat_write(memcard,3+i, NC_FAT_END_OF_LIST);
313   }
314
315   /* reserved at end of fat table - required?? */
316   memcard_fat_write(memcard,memcard->max_block_index-1, NC_FAT_RESERVED);
317
318   {
319      /* format for NC100 */
320      unsigned long dir_entry_offset = memcard_get_free_dir_entry(memcard);
321      int dir_size = NC_BLOCK_SIZE;
322      struct nc_card_dir_entry *dir_entry;
323
324      dir_entry = (struct nc_card_dir_entry *)&memcard->memcard_data[dir_entry_offset];
325
326      strcpy((char *)dir_entry->filename,(char *)"NC100");
327      dir_entry->size_high_byte = (dir_size>>8) & 0x0ff;
328      dir_entry->size_low_byte = (dir_size & 0x0ff);
329      dir_entry->first_block_high = 0x020;
330      dir_entry->first_block_low = 0x02;
331      dir_entry->type = NC_DIR_ENTRY_TYPE_DIR;
332   }
333}
334
335
336static unsigned long memcard_locate_dir_entry(struct nc_memcard *memcard,char *pNCFilename)
337{
338   int current_block = 2;
339   unsigned long offset;
340
341   while (current_block!=NC_FAT_END_OF_LIST)
342   {
343      int i;
344
345      offset = memcard_block_to_offset(current_block);
346
347      for (i=0; i<(NC_BLOCK_SIZE/32); i++)
348      {
349         if (memcard->memcard_data[offset]!=0)
350         {
351            if (memcmp(&memcard->memcard_data[offset], pNCFilename,12)==0)
352            {
353               return offset;
354            }
355         }
356     
357         offset+=32;
358      }
359
360      current_block = memcard_fat_get_next_block(memcard,current_block);
361     
362      if (current_block!=NC_FAT_END_OF_LIST)
363      {
364         current_block = current_block & 0x0fff;
365      }
366   }
367
368   return -1;
369}
370
371static int   memcard_del(struct nc_memcard *memcard,char *pNCFilename)
372{
373   unsigned long dir_entry_offset = memcard_locate_dir_entry(memcard,pNCFilename);
374   int success_code = 0;
375
376   if (dir_entry_offset!=-1)
377   {
378      int current_block;
379      struct nc_card_dir_entry *dir_entry;
380
381      dir_entry = (struct nc_card_dir_entry *)&memcard->memcard_data[dir_entry_offset];
382
383      /* get first block index from directory entry */
384      current_block = ((dir_entry->first_block_high & 0x0f)<<8) | dir_entry->first_block_low;
385
386      while (current_block!=0)
387      {
388         int next_block;
389     
390         /* get next block in list */
391         next_block = memcard_fat_get_next_block(memcard,current_block);
392         /* zero out this block */
393         memcard_fat_write(memcard,current_block,0);
394         
395         /* go to next block */
396         current_block = next_block;
397
398         if (current_block!=NC_FAT_END_OF_LIST)
399         {
400            current_block &= 0x0fff;
401         }
402      }
403
404      /* clear first char of filename */
405      dir_entry->filename[0] = '\0';
406      success_code = 1;
407   }
408
409   return success_code;
410}
411
412
413struct nc_card_image
414{
415   imgtool_image base;
416   imgtool_stream *file_handle;
417   struct nc_memcard memcard;
418};
419
420static int nc_card_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
421{
422   struct nc_card_image *nc_card;
423
424   *outimg = NULL;
425
426   nc_card = (struct nc_card_image *)malloc(sizeof(struct nc_card_image));
427
428   if (!nc_card)
429   {
430      return IMGTOOLERR_OUTOFMEMORY;
431   }
432
433   nc_card->file_handle = f;
434   nc_card->base.module = mod;
435
436   /* allocate a big chunk of memory for memcard data - max size will be 1mb! */
437   if (!memcard_init(&nc_card->memcard, stream_size(f)))
438   {
439      return IMGTOOLERR_OUTOFMEMORY;
440   }
441
442   /* read data into memcard */
443   if (stream_read(f, nc_card->memcard.memcard_data, nc_card->memcard.memcard_size)!=nc_card->memcard.memcard_size)
444   {
445      memcard_free(&nc_card->memcard);
446
447      return IMGTOOLERR_READERROR;
448   }
449
450   *outimg = (imgtool_image *)nc_card;
451   return 0;
452}
453
454static void nc_card_image_exit(imgtool_image *img)
455{
456   struct nc_card_image *nc_card = (struct nc_card_image *)img;
457
458   stream_seek(nc_card->file_handle, 0, SEEK_SET);
459   stream_write(nc_card->file_handle, nc_card->memcard.memcard_data, nc_card->memcard.memcard_size);
460   stream_close(nc_card->file_handle);
461
462   memcard_free(&nc_card->memcard);
463}
464
465
466/* count number of free blocks and calculate freespace */
467static size_t nc_card_image_freespace(imgtool_image *img)
468{
469   struct nc_card_image *nc_card = (struct nc_card_image *)img;
470   int i;
471   int count;
472
473   count = 0;
474   for (i=0; i<nc_card->memcard.max_block_index; i++)
475   {
476      if (memcard_fat_read(&nc_card->memcard,i)==0)
477      {
478         count++;
479      }
480   }
481   return count*NC_BLOCK_SIZE;
482}
483
484/* create a empty image */
485/* in this case a formatted image */
486static int nc_card_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
487{
488   int code;
489
490   struct nc_memcard memcard;
491   
492   /* allocate a big chunk of memory for memcard data - max size will be 1mb! */
493   if (!memcard_init(&memcard, 1024*1024))
494   {
495      return IMGTOOLERR_OUTOFMEMORY;
496   }
497
498   /* format the card */
499   memcard_format(&memcard);
500
501   /* write out */
502   code = 0;
503   if (stream_write(f, memcard.memcard_data, memcard.memcard_size) != memcard.memcard_size)
504   {
505      /* write error! */
506      code = IMGTOOLERR_WRITEERROR;
507   }
508
509   /* free memcard data */
510   memcard_free(&memcard);
511
512   /* return success or failure code */
513   return code;
514}
515
516static void setup_nc_filename(char *nc_filename, const char *fname)
517{
518   char ch;
519   int offset;
520
521   memset(nc_filename, 0, 12);
522
523   offset = 0;
524   do
525   {
526      /* get char */
527      ch = fname[offset];
528
529      if (ch!=0)
530      {
531         /* convert to upper case */
532         ch = toupper(ch);
533         nc_filename[offset] = ch;
534         offset++;
535      }
536   }
537   while ((ch!=0) && (offset<12));
538}
539
540static int nc_card_image_deletefile(imgtool_image *img, const char *fname)
541{
542   struct nc_card_image *nc_card = (struct nc_card_image *)img;
543   char nc_filename[12];
544
545   setup_nc_filename(nc_filename,fname);
546
547   if (memcard_del(&nc_card->memcard,nc_filename))
548   {
549      return IMGTOOLERR_MODULENOTFOUND;     
550   }
551
552   return 0;
553}
554
555
556
557/* get a file from the memcard */
558static int nc_card_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
559{
560   struct nc_card_image *nc_card = (struct nc_card_image *)img;
561   char nc_filename[12];
562   unsigned long dir_entry_offset;
563   
564   setup_nc_filename(nc_filename, fname);
565
566   dir_entry_offset = memcard_locate_dir_entry(&nc_card->memcard,(char *)nc_filename);
567
568   if (dir_entry_offset!=-1)
569   {
570      struct nc_card_dir_entry *dir_entry;
571      int current_block;
572      int length_remaining;
573
574      dir_entry = (struct nc_card_dir_entry *)&nc_card->memcard.memcard_data[dir_entry_offset];
575
576      /* get size of file from directory entry */
577      length_remaining = ((dir_entry->size_high_byte & 0x0ff)<<8) | (dir_entry->size_low_byte & 0x0ff);
578   
579      /* get first block index from directory entry */
580      current_block = ((dir_entry->first_block_high & 0x0f)<<8) | dir_entry->first_block_low;
581
582      /* keep going until we have written all data or we have got to end of block list */
583      while ((length_remaining!=0) && (current_block!=NC_FAT_END_OF_LIST))
584      {
585         unsigned long block_offset;
586         int copy_length;
587
588         /* get offset of block data in memcard data */
589         block_offset = memcard_block_to_offset(current_block);
590     
591         /* calc amount of data to copy from block */
592         if (length_remaining<NC_BLOCK_SIZE)
593         {
594            copy_length = length_remaining;
595         }
596         else
597         {
598            copy_length = NC_BLOCK_SIZE;
599         }
600
601         /* output to file */
602         if (stream_write(destf, &nc_card->memcard.memcard_data[block_offset], copy_length)!=copy_length)
603            return IMGTOOLERR_WRITEERROR;
604     
605         /* update length of data remaining to write */
606         length_remaining -=copy_length;   
607
608         /* get next block in list */
609         current_block = memcard_fat_get_next_block(&nc_card->memcard,current_block);
610         
611         if (current_block!=NC_FAT_END_OF_LIST)
612         {
613            current_block &= 0x0fff;
614         }
615      }
616   }
617
618   return 0;
619}
620
621/* put a file to the memcard */
622static int nc_card_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_)
623{
624   struct nc_card_image *nc_card = (struct nc_card_image *)img;
625   unsigned long length;
626   unsigned long offset;
627
628   char nc_filename[12];
629
630   length = stream_size(sourcef);
631
632   /* locate a free directory entry */
633   offset = memcard_get_free_dir_entry(&nc_card->memcard);
634
635   setup_nc_filename(nc_filename, fname);
636
637   if (offset!=-1)
638   {
639      /* got a directory entry */
640
641      int   current_block;
642      int previous_block;
643      unsigned long block_offset;
644      unsigned long file_offset = 0;
645      unsigned long length_remaining = length;
646      struct nc_card_dir_entry *dir_entry;
647      int copy_length;
648
649      /* do not transfer more then 65536 bytes */
650      /* this is max size of file on card */
651      /* file size specified with 2 bytes only! */
652      if (length_remaining>65536)
653      {
654         length_remaining = 65536;
655      }
656
657      /* locate the first free block */
658      current_block = memcard_fat_get_free_block(&nc_card->memcard);
659
660      if (current_block!=-1)
661      {
662         /* initialise directory entry - blank all entries */
663         memset(&nc_card->memcard.memcard_data[offset], 0, 32);
664
665         dir_entry = (struct nc_card_dir_entry *)&nc_card->memcard.memcard_data[offset];
666         /* set size of file in directory entry */
667         dir_entry->size_high_byte = (length>>8) & 0x0ff;
668         dir_entry->size_low_byte = length & 0x0ff;
669         /* set first block in directory entry */
670         dir_entry->first_block_high = ((current_block>>8) & 0x0f) | 0x020;
671         dir_entry->first_block_low = (current_block & 0x0ff);
672         /* setup filename */
673         strncpy((char *)dir_entry->filename,(char *)nc_filename, 12);
674         
675         while (length_remaining!=0)
676         {
677            /* get offset of block data */
678            block_offset = memcard_block_to_offset(current_block);
679         
680            /* calc amount of data to copy to block */
681            if (length_remaining<NC_BLOCK_SIZE)
682            {
683               copy_length = length_remaining;
684            }
685            else
686            {
687               copy_length = NC_BLOCK_SIZE;
688            }
689
690            /* copy data to memcard */
691            if (stream_read(sourcef, &nc_card->memcard.memcard_data[block_offset], copy_length)!=copy_length)
692               return IMGTOOLERR_WRITEERROR;
693
694            length_remaining -=copy_length;   
695            file_offset+=copy_length;
696
697            /* mark block as used */
698            memcard_fat_write(&nc_card->memcard,current_block, NC_FAT_END_OF_LIST);
699
700            previous_block = current_block;
701            current_block = memcard_fat_get_free_block(&nc_card->memcard);
702     
703            if (current_block==-1)
704               break;
705         
706            /* link up block chain */
707            memcard_fat_write(&nc_card->memcard,previous_block, current_block|0x02000);
708         }
709     
710         /* end block chain */
711         memcard_fat_write(&nc_card->memcard,current_block, NC_FAT_END_OF_LIST);
712      }
713   }
714
715
716   return 0;
717}
718
719/* directory fills 1 or more blocks.
720current_block holds index of current block we are accessing,
721offset_in_block holds offset within block referenced by current_block.
722eod is 1 if end of directory (no more blocks) or 0 if not end of directory */
723
724struct nc_card_direnum
725{
726   imgtool_directory base;
727   /* card image */
728   struct nc_card_image *img;
729   /* directory block index */
730   int current_block;
731   /* index of entry within block */
732   int offset_in_block;
733   /* true if reached last entry in last directory block */
734   int eod;
735};
736
737
738static int nc_card_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
739{
740   struct nc_card_image *nc_card = (struct nc_card_image *)img;
741   struct nc_card_direnum *card_enum;
742
743   if (memcard_is_executable(&nc_card->memcard))
744   {
745      return IMGTOOLERR_MODULENOTFOUND;
746   }   
747
748   card_enum = (struct nc_card_direnum *) malloc(sizeof(struct nc_card_direnum));
749   if (!card_enum)
750      return IMGTOOLERR_OUTOFMEMORY;
751
752   card_enum->base.module = img->module;
753   card_enum->img = (struct nc_card_image *) img;
754   /* directory always starts on block 2 */
755   card_enum->current_block = 2;
756   card_enum->offset_in_block = 0;
757   card_enum->eod = 0;
758   *outenum = &card_enum->base;
759   return 0;
760}
761
762static int nc_card_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
763{
764   struct nc_card_direnum *card_enum = (struct nc_card_direnum *) enumeration;
765
766   /* got to end of directory? */
767   if (!card_enum->eod)
768   {
769      int quit = 0;
770      /* no */
771
772      /* loop until we get a used directory entry */
773      while (quit==0)
774      {
775         int dir_block_offset;
776         struct nc_card_dir_entry *dir_entry;
777
778         /* gone over end of block? */
779         if (card_enum->offset_in_block==NC_BLOCK_SIZE)
780         {
781            /* yes */
782
783            /* reset offset */
784            card_enum->offset_in_block = 0;
785            /* get next block */
786            card_enum->current_block = memcard_fat_get_next_block(&card_enum->img->memcard,card_enum->current_block);
787
788            /* block index = end of list? */
789            if (card_enum->current_block==NC_FAT_END_OF_LIST)
790            {
791               /* yes */
792
793               /* no more directory blocks, end of directory reached */
794               card_enum->eod = 1;
795     
796               /* no more blocks - so quit */
797               quit = 1;
798            }
799            else
800            {
801               /* strip off upper 4 bits */
802               card_enum->current_block &=0x0fff;
803            }
804         }
805
806         if (quit==0)
807         {
808            dir_block_offset = memcard_block_to_offset(card_enum->current_block);
809
810            dir_entry = (struct nc_card_dir_entry *)&card_enum->img->memcard.memcard_data[dir_block_offset + card_enum->offset_in_block];
811
812            if (dir_entry->filename[0]!=0)
813            {   
814               /* got a used directory entry */
815
816               if (ent->fname_len<13)
817                  return IMGTOOLERR_BUFFERTOOSMALL;
818
819               memcpy(ent->fname, dir_entry->filename,12);
820               dir_entry->filename[12] = '\0';
821
822               /* set file-size -> from directory */
823               ent->filesize = ((dir_entry->size_high_byte & 0x0ff)<<8) | (dir_entry->size_low_byte & 0x0ff);
824
825               /* not last entry */
826               ent->eof = 0;
827               /* not corrupt */
828               ent->corrupt = 0;
829
830               if (ent->attr_len)
831               {   
832                  switch (dir_entry->type)
833                  {
834                     case 0:
835                     {
836                        sprintf(ent->attr,"ASCII FILE");
837                     }
838                     break;
839
840                     case 5:
841                     {
842                        sprintf(ent->attr,"BASIC FILE");
843                     }
844                     break;
845
846                     case 3:
847                     {
848                        sprintf(ent->attr,"DIRECTORY");
849                     }
850                     break;
851                  }
852               }
853
854               quit = 1;
855            }
856         }
857
858         /* update offset for next enum */
859         card_enum->offset_in_block+=32;
860      }
861   }
862
863   /* got to end of directory? */
864   if (card_enum->eod)
865   {
866      /* yes */
867      ent->filesize = 0;
868      ent->corrupt = 0;
869      ent->eof = 1;
870      if (ent->fname_len > 0)
871         ent->fname[0] = '\0';
872   }
873
874   return 0;
875}
876
877static void nc_card_image_closeenum(imgtool_directory *enumeration)
878{
879   free(enumeration);
880}
src/mess/tools/imgtool/modules/lynx.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include "osdepend.h"
5#include "imgtoolx.h"
6
7/* commodore 64 lynx format
8   motivation
9   stuff several files in one file, for archiving and transmission?
10   no packing?
11
12   commodore basic header
13   ended with 0 0 0 0x0d
14   string count begin of data in 254 byte blocks 0x0d
15
16   string count of entries in directory 0x0d
17
18   count of entries
19    name 0x13
20   string blocks 0x13
21   char type 0x13
22   string bytes_in_last_block 0x13
23
24   data for the entries
25    filled up to 254 byte blocks
26
27*/
28
29typedef struct {
30   char name[21];
31   int offset, size;
32   char filetype;
33} LYNX_ENTRY;
34
35typedef struct {
36   imgtool_image base;
37   imgtool_stream *file_handle;
38   int size;
39   unsigned char *data;
40   int count;
41   LYNX_ENTRY *entries;
42} lynx_image;
43
44typedef struct {
45   imgtool_directory base;
46   lynx_image *image;
47   int index;
48} lynx_iterator;
49
50static int lynx_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
51static void lynx_image_exit(imgtool_image *img);
52//static void lynx_image_info(imgtool_image *img, char *string, const int len);
53static int lynx_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
54static int lynx_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
55static void lynx_image_closeenum(imgtool_directory *enumeration);
56static int lynx_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
57
58IMAGEMODULE(
59   lynx,
60   "Commodore 64 Archive",   /* human readable name */
61   "lnx",                        /* file extension */
62   NULL,                        /* crcfile */
63   NULL,                        /* crc system name */
64   NULL,                        /* eoln */
65   0,                           /* flags */
66   lynx_image_init,            /* init function */
67   lynx_image_exit,            /* exit function */
68   NULL,//lynx_image_info,      /* info function */
69   lynx_image_beginenum,         /* begin enumeration */
70   lynx_image_nextenum,         /* enumerate next */
71   lynx_image_closeenum,         /* close enumeration */
72   NULL,/* free space on image */
73   lynx_image_readfile,         /* read file */
74   NULL,/* write file */
75   NULL,/* delete file */
76   NULL,/* create image */
77   NULL,                        /* read sector */
78   NULL,                        /* write sector */
79   NULL,                        /* file options */
80   NULL                        /* create options */
81)
82
83static int lynx_read_line(lynx_image *image, int pos)
84{
85   int i;
86   for (i=0; (pos+i<image->size)&&(image->data[pos+i]!=0xd); i++ ) ;
87   if (pos+i<image->size) i++;
88   return i;
89}
90
91static int lynx_read_image(lynx_image *image)
92{
93   int i=0, j, n;
94
95   n=lynx_read_line(image, i);
96   if ( n==0 ) return IMGTOOLERR_CORRUPTIMAGE;
97   i+=n;
98
99   n=lynx_read_line(image, i);
100   j=atoi((char *)image->data+i); /* begin of data */
101   if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
102   i+=n;
103
104   n=lynx_read_line(image, i);
105   image->count=atoi((char *)image->data+i);
106   if ((n==0)||(image->count==0)) return IMGTOOLERR_CORRUPTIMAGE;
107   i+=n;
108
109   image->entries=malloc(sizeof(LYNX_ENTRY)*image->count);
110   if (!image->entries) return IMGTOOLERR_OUTOFMEMORY;
111
112   image->entries[0].offset=j*254;
113
114   for (j=0; j<image->count; j++) {
115      int a,b;
116
117      n=lynx_read_line(image, i);
118      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
119      strncpy(image->entries[j].name,(char *)image->data+i, n-1);
120      i+=n;
121
122      n=lynx_read_line(image, i);
123      a=atoi((char *)image->data+i);
124      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
125      i+=n;
126
127      n=lynx_read_line(image, i);
128      image->entries[j].filetype=image->data[i];
129      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
130      i+=n;
131
132      n=lynx_read_line(image, i);
133      b=atoi((char *)image->data+i);
134      if ((n==0)) return IMGTOOLERR_CORRUPTIMAGE;
135      i+=n;
136
137      image->entries[j].size=(a-1)*254+b-1;
138      if (j+1<image->count)
139         image->entries[j+1].offset=image->entries[j].offset+254*a;
140   }
141
142   return 0;
143}
144
145static int lynx_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
146{
147   lynx_image *image;
148   int rc;
149
150   image=*(lynx_image**)outimg=(lynx_image *) malloc(sizeof(lynx_image));
151   if (!image) return IMGTOOLERR_OUTOFMEMORY;
152
153   memset(image, 0, sizeof(lynx_image));
154   image->base.module = mod;
155   image->size=stream_size(f);
156   image->file_handle=f;
157
158   image->data = (unsigned char *) malloc(image->size);
159   if ( (!image->data)
160       ||(stream_read(f, image->data, image->size)!=image->size) ) {
161      free(image);
162      *outimg=NULL;
163      return IMGTOOLERR_OUTOFMEMORY;
164   }
165   if ( (rc=lynx_read_image(image)) ) {
166      if (image->entries) free(image->entries);
167      free(image);
168      *outimg=NULL;
169      return rc;
170   }
171
172   return 0;
173}
174
175static void lynx_image_exit(imgtool_image *img)
176{
177   lynx_image *image=(lynx_image*)img;
178   stream_close(image->file_handle);
179   free(image->entries);
180   free(image->data);
181   free(image);
182}
183
184#if 0
185static void lynx_image_info(imgtool_image *img, char *string, const int len)
186{
187   lynx_image *image=(lynx_image*)img;
188   char dostext_with_null[33]= { 0 };
189   char name_with_null[25]={ 0 };
190   strncpy(dostext_with_null, HEADER(image)->dostext, 32);
191   strncpy(name_with_null, HEADER(image)->description, 24);
192   sprintf(string,"%s\n%s\nversion:%.4x max entries:%d",
193         dostext_with_null,
194         name_with_null,
195         GET_UWORD(HEADER(image)->version),
196         HEADER(image)->max_entries);
197}
198#endif
199
200static int lynx_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
201{
202   lynx_image *image=(lynx_image*)img;
203   lynx_iterator *iter;
204
205   iter=*(lynx_iterator**)outenum = (lynx_iterator *) malloc(sizeof(lynx_iterator));
206   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
207
208   iter->base.module = img->module;
209
210   iter->image=image;
211   iter->index = 0;
212   return 0;
213}
214
215static int lynx_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
216{
217   lynx_iterator *iter=(lynx_iterator*)enumeration;
218   ent->corrupt=0;
219   
220   ent->eof=iter->index>=iter->image->count;
221   if (!ent->eof) {
222      strcpy(ent->fname, iter->image->entries[iter->index].name);
223      if (ent->attr) {
224         switch (iter->image->entries[iter->index].filetype) {
225         case 'P': strcpy(ent->attr,"PRG");break;
226         case 'S': strcpy(ent->attr,"SEQ");break;
227         case 'R': strcpy(ent->attr,"REL");break;
228         case 'U': strcpy(ent->attr,"USR");break;
229         default:
230            sprintf(ent->attr,"type:%c",
231                  iter->image->entries[iter->index].filetype );
232         }
233      }
234      ent->filesize=iter->image->entries[iter->index].size;
235      iter->index++;
236   }
237   return 0;
238}
239
240static void lynx_image_closeenum(imgtool_directory *enumeration)
241{
242   free(enumeration);
243}
244
245static LYNX_ENTRY* lynx_image_findfile(lynx_image *image, const char *fname)
246{
247   int i;
248
249   for (i=0; i<image->count; i++) {
250      if (!mame_stricmp(fname, image->entries[i].name) ) return image->entries+i;
251   }
252   return NULL;
253}
254
255static int lynx_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
256{
257   lynx_image *image=(lynx_image*)img;
258   LYNX_ENTRY *entry;
259
260   if ((entry=lynx_image_findfile(image, fname))==NULL ) return IMGTOOLERR_MODULENOTFOUND;
261
262   if (stream_write(destf, image->data+entry->offset, entry->size)!=entry->size) {
263      return IMGTOOLERR_WRITEERROR;
264   }
265
266   return 0;
267}
268
src/mess/tools/imgtool/modules/rsdos.c
r0r1340
1/****************************************************************************
2
3   rsdos.c
4
5   CoCo RS-DOS disk images
6
7****************************************************************************/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include "osdepend.h"
13#include "imgtoolx.h"
14#include "utils.h"
15#include "formats/coco_dsk.h"
16#include "iflopimg.h"
17#include "utils.h"
18
19
20/* this structure mirrors the structure of an RS-DOS directory entry on disk */
21struct rsdos_dirent
22{
23   char fname[8];
24   char fext[3];
25   char ftype;
26   char asciiflag;
27   unsigned char first_granule;
28   unsigned char lastsectorbytes_msb;
29   unsigned char lastsectorbytes_lsb;
30   unsigned char unused[16];
31};
32
33struct rsdos_direnum
34{
35   int index;
36   int eof;
37};
38
39#define RSDOS_OPTIONS_FTYPE      'T'
40#define RSDOS_OPTIONS_ASCII      'M'
41
42
43
44/*********************************************************************
45   Imgtool module code
46*********************************************************************/
47
48#define MAX_DIRENTS      ((18-2)*(256/32))
49static floperr_t get_rsdos_dirent(imgtool_image *f, int index_loc, struct rsdos_dirent *ent)
50{
51   return floppy_read_sector(imgtool_floppy(f), 0, 17, 3, index_loc * 32, (void *) ent, sizeof(*ent));
52}
53
54
55
56static floperr_t put_rsdos_dirent(imgtool_image *f, int index_loc, const struct rsdos_dirent *ent)
57{
58   if (index_loc >= MAX_DIRENTS)
59      return IMGTOOLERR_FILENOTFOUND;
60   return floppy_write_sector(imgtool_floppy(f), 0, 17, 3, index_loc * 32, (void *) ent, sizeof(*ent));
61}
62
63
64
65/* fnamebuf must have at least 13 bytes */
66static void get_dirent_fname(char *fnamebuf, const struct rsdos_dirent *ent)
67{
68   char *s;
69
70   memset(fnamebuf, 0, 13);
71   memcpy(fnamebuf, ent->fname, sizeof(ent->fname));
72   rtrim(fnamebuf);
73   s = fnamebuf + strlen(fnamebuf);
74   *(s++) = '.';
75   memcpy(s, ent->fext, sizeof(ent->fext));
76   rtrim(s);
77
78   /* If no extension, remove period */
79   if (*s == '\0')
80      s[-1] = '\0';
81}
82
83
84
85static imgtoolerr_t lookup_rsdos_file(imgtool_image *f, const char *fname, struct rsdos_dirent *ent, int *position)
86{
87   int i;
88   floperr_t ferr;
89   char fnamebuf[13];
90
91   i = 0;
92   fnamebuf[0] = '\0';
93
94   do
95   {
96      do
97      {
98         ferr = get_rsdos_dirent(f, i++, ent);
99         if (ferr)
100            return imgtool_floppy_error(ferr);
101      }
102      while(ent->fname[0] == '\0');
103
104
105      if (ent->fname[0] != -1)
106         get_dirent_fname(fnamebuf, ent);
107   }
108   while((ent->fname[0] != -1) && mame_stricmp(fnamebuf, fname));
109
110   if (ent->fname[0] == -1)
111      return IMGTOOLERR_FILENOTFOUND;
112
113   if (position)
114      *position = i - 1;
115   return 0;
116}
117
118
119
120static UINT8 get_granule_count(imgtool_image *img)
121{
122   UINT16 tracks;
123   UINT16 granules;
124
125   tracks = floppy_get_tracks_per_disk(imgtool_floppy(img));
126   granules = (tracks - 1) * 2;
127   return (granules > 255) ? 255 : (UINT8) granules;
128}
129
130#define MAX_GRANULEMAP_SIZE   256
131
132/* granule_map must be an array of MAX_GRANULEMAP_SIZE bytes */
133static floperr_t get_granule_map(imgtool_image *img, UINT8 *granule_map, UINT8 *granule_count)
134{
135   UINT8 count;
136
137   count = get_granule_count(img);
138   if (granule_count)
139      *granule_count = count;
140
141   return floppy_read_sector(imgtool_floppy(img), 0, 17, 2, 0, granule_map, count);
142}
143
144
145
146static floperr_t put_granule_map(imgtool_image *img, const UINT8 *granule_map, UINT8 granule_count)
147{
148   return floppy_write_sector(imgtool_floppy(img), 0, 17, 2, 0, granule_map, granule_count);
149}
150
151
152
153
154static imgtoolerr_t transfer_granule(imgtool_image *img, UINT8 granule, int length, imgtool_stream *f, imgtoolerr_t (*proc)(imgtool_image *, int, int, int, int, size_t, imgtool_stream *))
155{
156   imgtoolerr_t err = IMGTOOLERR_SUCCESS;
157   UINT8 track, sector;
158
159   track = granule / 2;
160   if (track >= 17)
161      track++;
162
163   sector = (granule % 2) ? 10 : 1;
164
165   if (length > 0)
166      err = proc(img, 0, track, sector, 0, length, f);
167   return err;
168}
169
170
171
172static imgtoolerr_t transfer_from_granule(imgtool_image *img, UINT8 granule, int length, imgtool_stream *destf)
173{
174   return transfer_granule(img, granule, length, destf, imgtool_floppy_read_sector_to_stream);
175}
176
177
178
179static imgtoolerr_t transfer_to_granule(imgtool_image *img, UINT8 granule, int length, imgtool_stream *sourcef)
180{
181   return transfer_granule(img, granule, length, sourcef, imgtool_floppy_write_sector_from_stream);
182}
183
184
185
186static imgtoolerr_t process_rsdos_file(struct rsdos_dirent *ent, imgtool_image *img, imgtool_stream *destf, size_t *size)
187{
188   floperr_t ferr;
189   size_t s, lastgransize;
190   UINT8 granule_count;
191   unsigned char i = 0, granule;
192   UINT8 usedmap[MAX_GRANULEMAP_SIZE];   /* Used to detect infinite loops */
193   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
194
195   ferr = get_granule_map(img, granule_map, &granule_count);
196   if (ferr)
197      return imgtool_floppy_error(ferr);
198
199   memset(usedmap, 0, granule_count);
200
201   lastgransize = ent->lastsectorbytes_lsb + (((int) ent->lastsectorbytes_msb) << 8);
202   s = 0;
203   granule = ent->first_granule;
204
205   while(!usedmap[granule] && ((i = granule_map[granule]) < granule_count))
206   {
207      usedmap[granule] = 1;
208      if (destf)
209         transfer_from_granule(img, granule, 9*256, destf);
210
211      /* i is the next granule */
212      s += (256 * 9);
213      granule = i;
214   }
215
216   if ((i < 0xc0) || (i > 0xc9))
217      return IMGTOOLERR_CORRUPTIMAGE;
218
219   if (lastgransize)
220      i--;
221   lastgransize += (256 * (i - 0xc0));
222
223   if (destf)
224      transfer_from_granule(img, granule, lastgransize, destf);
225
226   if (size)
227      *size = s + lastgransize;
228   return IMGTOOLERR_SUCCESS;
229}
230
231
232
233/* create a new directory entry with a specified name */
234static imgtoolerr_t prepare_dirent(struct rsdos_dirent *ent, const char *fname)
235{
236   const char *fname_end;
237   const char *fname_ext;
238   int fname_ext_len;
239
240   memset(ent, '\0', sizeof(*ent));
241   memset(ent->fname, ' ', sizeof(ent->fname));
242   memset(ent->fext, ' ', sizeof(ent->fext));
243
244   fname_end = strchr(fname, '.');
245   if (fname_end)
246      fname_ext = fname_end + 1;
247   else
248      fname_end = fname_ext = fname + strlen(fname);
249
250   fname_ext_len = strlen(fname_ext);
251
252   /* We had better be an 8.3 filename */
253   if (((fname_end - fname) > 8) || (fname_ext_len > 3))
254      return IMGTOOLERR_BADFILENAME;
255
256   memcpy(ent->fname, fname, fname_end - fname);
257   memcpy(ent->fext, fname_ext, fname_ext_len);
258
259   /* For now, all files are type 2 binary files */
260   ent->ftype = 2;
261   ent->asciiflag = 0;
262   return IMGTOOLERR_SUCCESS;
263}
264
265
266
267static imgtoolerr_t rsdos_diskimage_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
268{
269   floperr_t ferr;
270   imgtoolerr_t err;
271   size_t filesize;
272   struct rsdos_direnum *rsenum;
273   struct rsdos_dirent rsent;
274   char fname[13];
275   imgtool_image *image;
276
277   image = imgtool_directory_image(enumeration);
278   rsenum = (struct rsdos_direnum *) imgtool_directory_extrabytes(enumeration);
279
280   /* Did we hit the end of file before? */
281   if (rsenum->eof)
282      goto eof;
283
284   do
285   {
286      if (rsenum->index >= MAX_DIRENTS)
287         goto eof;
288
289      ferr = get_rsdos_dirent(image, rsenum->index++, &rsent);
290      if (ferr)
291         return imgtool_floppy_error(ferr);
292   }
293   while(rsent.fname[0] == '\0');
294
295   /* Now are we at the eof point? */
296   if (rsent.fname[0] == -1)
297   {
298      rsenum->eof = 1;
299eof:
300      ent->eof = 1;
301   }
302   else
303   {
304      /* Not the end of file */
305      err = process_rsdos_file(&rsent, image, NULL, &filesize);
306      if (err)
307         return err;
308
309      if (filesize == ((size_t) -1))
310      {
311         /* corrupt! */
312         ent->filesize = 0;
313         ent->corrupt = 1;
314      }
315      else
316      {
317         ent->filesize = filesize;
318         ent->corrupt = 0;
319      }
320      ent->eof = 0;
321
322      get_dirent_fname(fname, &rsent);
323
324      snprintf(ent->filename, sizeof(ent->filename) / sizeof(ent->filename[0]), "%s", fname);
325      snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%d %c", (int) rsent.ftype, (char) (rsent.asciiflag + 'B'));
326   }
327   return IMGTOOLERR_SUCCESS;
328}
329
330
331
332static imgtoolerr_t rsdos_diskimage_freespace(imgtool_partition *partition, UINT64 *size)
333{
334   floperr_t ferr;
335   UINT8 i;
336   size_t s = 0;
337   UINT8 granule_count;
338   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
339   imgtool_image *image = imgtool_partition_image(partition);
340
341   ferr = get_granule_map(image, granule_map, &granule_count);
342   if (ferr)
343      return imgtool_floppy_error(ferr);
344
345   for (i = 0; i < granule_count; i++)
346   {
347      if (granule_map[i] == 0xff)
348         s += (9 * 256);
349   }
350   *size = s;
351   return FLOPPY_ERROR_SUCCESS;
352}
353
354
355
356static imgtoolerr_t delete_entry(imgtool_image *img, struct rsdos_dirent *ent, int pos)
357{
358   floperr_t ferr;
359   unsigned char g, i;
360   UINT8 granule_count;
361   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
362
363   /* Write a NUL in the filename, marking it deleted */
364   ent->fname[0] = 0;
365   ferr = put_rsdos_dirent(img, pos, ent);
366   if (ferr)
367      return imgtool_floppy_error(ferr);
368
369   ferr = get_granule_map(img, granule_map, &granule_count);
370   if (ferr)
371      return imgtool_floppy_error(ferr);
372
373   /* Now free up the granules */
374   g = ent->first_granule;
375   while (g < granule_count)
376   {
377      i = granule_map[g];
378      granule_map[g] = 0xff;
379      g = i;
380   }
381
382   ferr = put_granule_map(img, granule_map, granule_count);
383   if (ferr)
384      return imgtool_floppy_error(ferr);
385
386   return IMGTOOLERR_SUCCESS;
387}
388
389
390
391static imgtoolerr_t rsdos_diskimage_readfile(imgtool_partition *partition, const char *fname, const char *fork, imgtool_stream *destf)
392{
393   imgtoolerr_t err;
394   struct rsdos_dirent ent;
395   size_t size;
396   imgtool_image *img = imgtool_partition_image(partition);
397
398   err = lookup_rsdos_file(img, fname, &ent, NULL);
399   if (err)
400      return err;
401
402   err = process_rsdos_file(&ent, img, destf, &size);
403   if (err)
404      return err;
405
406   if (size == (size_t) -1)
407      return IMGTOOLERR_CORRUPTIMAGE;
408
409   return 0;
410}
411
412
413
414static imgtoolerr_t rsdos_diskimage_writefile(imgtool_partition *partition, const char *fname, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
415{
416   floperr_t ferr;
417   imgtoolerr_t err;
418   imgtool_image *img = imgtool_partition_image(partition);
419   struct rsdos_dirent ent, ent2;
420   size_t i;
421   UINT64 sz;
422   UINT64 freespace = 0;
423   unsigned char g;
424   unsigned char *gptr;
425   UINT8 granule_count;
426   UINT8 granule_map[MAX_GRANULEMAP_SIZE];
427
428   /* can we write to this image? */
429   if (floppy_is_read_only(imgtool_floppy(img)))
430      return IMGTOOLERR_READONLY;
431
432   err = rsdos_diskimage_freespace(partition, &freespace);
433   if (err)
434      return err;
435
436   /* is there enough space? */
437   sz = stream_size(sourcef);
438   if (sz > freespace)
439      return IMGTOOLERR_NOSPACE;
440
441   /* setup our directory entry */
442   err = prepare_dirent(&ent, fname);
443   if (err)
444      return err;
445
446   ent.ftype = option_resolution_lookup_int(writeoptions, RSDOS_OPTIONS_FTYPE);
447   ent.asciiflag = ((UINT8) option_resolution_lookup_int(writeoptions, RSDOS_OPTIONS_ASCII)) - 1;
448   ent.lastsectorbytes_lsb = sz % 256;
449   ent.lastsectorbytes_msb = (((sz % 256) == 0) && (sz > 0)) ? 1 : 0;
450   gptr = &ent.first_granule;
451
452   ferr = get_granule_map(img, granule_map, &granule_count);
453   if (ferr)
454      return imgtool_floppy_error(ferr);
455
456   g = 0x00;
457
458   do
459   {
460      while (granule_map[g] != 0xff)
461      {
462         g++;
463         if ((g >= granule_count) || (g == 0))
464            return IMGTOOLERR_UNEXPECTED;   /* We should have already verified that there is enough space */
465      }
466      *gptr = g;
467      gptr = &granule_map[g];
468
469
470      i = MIN(sz, (9*256));
471      err = transfer_to_granule(img, g, i, sourcef);
472      if (err)
473         return err;
474
475      sz -= i;
476
477      /* Go to next granule */
478      g++;
479   }
480   while(sz > 0);
481
482   /* Now that we are done with the file, we need to specify the final entry
483    * in the file allocation table
484    */
485   *gptr = 0xc0 + ((i + 255) / 256);
486
487   /* Now we need to find an empty directory entry */
488   i = -1;
489   do
490   {
491      ferr = get_rsdos_dirent(img, ++i, &ent2);
492      if (ferr)
493         return imgtool_floppy_error(ferr);
494   }
495   while((ent2.fname[0] != '\0') && strcmp(ent.fname, ent2.fname) && (ent2.fname[0] != -1));
496
497   /* delete file if it already exists */
498   if (ent2.fname[0] && (ent2.fname[0] != -1))
499   {
500      err = delete_entry(img, &ent2, i);
501      if (err)
502         return err;
503   }
504
505   ferr = put_rsdos_dirent(img, i, &ent);
506   if (ferr)
507      return imgtool_floppy_error(ferr);
508
509   /* write the granule map back out */
510   ferr = put_granule_map(img, granule_map, granule_count);
511   if (ferr)
512      return imgtool_floppy_error(ferr);
513
514   return IMGTOOLERR_SUCCESS;
515}
516
517
518
519static imgtoolerr_t rsdos_diskimage_deletefile(imgtool_partition *partition, const char *fname)
520{
521   imgtoolerr_t err;
522   imgtool_image *image = imgtool_partition_image(partition);
523   int pos;
524   struct rsdos_dirent ent;
525
526   err = lookup_rsdos_file(image, fname, &ent, &pos);
527   if (err)
528      return err;
529
530   return delete_entry(image, &ent, pos);
531}
532
533
534
535static imgtoolerr_t rsdos_diskimage_suggesttransfer(imgtool_partition *partition, const char *fname, imgtool_transfer_suggestion *suggestions, size_t suggestions_length)
536{
537   imgtoolerr_t err;
538   imgtool_image *image = imgtool_partition_image(partition);
539   struct rsdos_dirent ent;
540   int pos;
541
542   if (fname)
543   {
544      err = lookup_rsdos_file(image, fname, &ent, &pos);
545      if (err)
546         return err;
547
548      if (ent.asciiflag == (char) 0xFF)
549      {
550         /* ASCII file */
551         suggestions[0].viability = SUGGESTION_RECOMMENDED;
552         suggestions[0].filter = filter_eoln_getinfo;
553         suggestions[1].viability = SUGGESTION_POSSIBLE;
554         suggestions[1].filter = NULL;
555      }
556      else if (ent.ftype == 0)
557      {
558         /* tokenized BASIC file */
559         suggestions[0].viability = SUGGESTION_RECOMMENDED;
560         suggestions[0].filter = NULL;
561         suggestions[1].viability = SUGGESTION_POSSIBLE;
562         suggestions[1].filter = filter_cocobas_getinfo;
563      }
564   }
565   else
566   {
567      suggestions[0].viability = SUGGESTION_RECOMMENDED;
568      suggestions[0].filter = NULL;
569      suggestions[1].viability = SUGGESTION_POSSIBLE;
570      suggestions[1].filter = filter_eoln_getinfo;
571   }
572
573   return IMGTOOLERR_SUCCESS;
574}
575
576
577
578/*********************************************************************
579   Imgtool module declaration
580*********************************************************************/
581
582OPTION_GUIDE_START( coco_rsdos_writefile_optionguide )
583   OPTION_ENUM_START(   RSDOS_OPTIONS_FTYPE, "ftype", "File type" )
584      OPTION_ENUM(   0,      "basic",      "Basic" )
585      OPTION_ENUM(   1,      "data",         "Data" )
586      OPTION_ENUM(   2,      "binary",      "Binary" )
587      OPTION_ENUM(   3,      "assembler",   "Assembler Source" )
588   OPTION_ENUM_END
589   OPTION_ENUM_START(   RSDOS_OPTIONS_ASCII, "ascii", "Ascii flag" )
590      OPTION_ENUM(   0,      "ascii",      "Ascii" )
591      OPTION_ENUM(   1,      "binary",      "Binary" )
592   OPTION_ENUM_END
593OPTION_GUIDE_END
594
595
596
597void rsdos_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
598{
599   switch(state)
600   {
601      /* --- the following bits of info are returned as 64-bit signed integers --- */
602      case IMGTOOLINFO_INT_PREFER_UCASE:               info->i = 1; break;
603      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(struct rsdos_direnum); break;
604
605      /* --- the following bits of info are returned as NULL-terminated strings --- */
606      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "rsdos"); break;
607      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "RS-DOS format"); break;
608      case IMGTOOLINFO_STR_FILE:                     strcpy(info->s = imgtool_temp_str(), __FILE__); break;
609      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
610      case IMGTOOLINFO_STR_WRITEFILE_OPTSPEC:            strcpy(info->s = imgtool_temp_str(), "T0-[2]-3;M0-[1]"); break;
611
612      /* --- the following bits of info are returned as pointers to data or functions --- */
613      case IMGTOOLINFO_PTR_MAKE_CLASS:               info->make_class = imgtool_floppy_make_class; break;
614      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = rsdos_diskimage_nextenum; break;
615      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = rsdos_diskimage_freespace; break;
616      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = rsdos_diskimage_readfile; break;
617      case IMGTOOLINFO_PTR_WRITE_FILE:               info->write_file = rsdos_diskimage_writefile; break;
618      case IMGTOOLINFO_PTR_DELETE_FILE:               info->delete_file = rsdos_diskimage_deletefile; break;
619      case IMGTOOLINFO_PTR_SUGGEST_TRANSFER:            info->suggest_transfer = rsdos_diskimage_suggesttransfer; break;
620      case IMGTOOLINFO_PTR_WRITEFILE_OPTGUIDE:         info->writefile_optguide = coco_rsdos_writefile_optionguide; break;
621      case IMGTOOLINFO_PTR_FLOPPY_FORMAT:               info->p = (void *) floppyoptions_coco; break;
622   }
623}
src/mess/tools/imgtool/modules/ti990hd.c
r0r1340
1/*
2   Handlers for ti990 disk images
3
4   Disk images are in MESS format.
5
6   Raphael Nabet, 2003
7*/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <limits.h>
13#include <assert.h>
14#include "osdepend.h"
15#include "imgtoolx.h"
16
17/* Max sector lenght is bytes.  Generally 256, except for a few older disk
18units which use 288-byte-long sectors, and SCSI units which generally use
19standard 512-byte-long sectors. */
20/* I chose a limit of 512.  No need to use more until someone creates CD-ROMs
21for TI990. */
22#define MAX_SECTOR_SIZE 512
23#define MIN_SECTOR_SIZE 256
24
25#define MAX_CYLINDERS 2047
26#define MAX_HEADS 31
27#define MAX_SECTORS_PER_TRACK 256   /* 255 for 512-byte-long sector, so that the total number of words that can be recorded on a track may fit in one 16-bit word (store registers command) */
28
29/* Max path len in chars: this value is 48 characters in DX10, but since the
30path includes at least a leading '.', our value is 47. */
31/* Since path generally include a volume name that can be up to 8 character
32long, we should display a warning message when the user wants to create a path
33that is longer than 39 characters. */
34#define MAX_PATH_LEN 47
35#define MAX_SAFE_PATH_LEN 39
36
37#define MAX_DIR_LEVEL 25   /* We need to put a recursion limit to avoid endless recursion hazard */
38 
39
40typedef struct UINT16BE
41{
42   UINT8 bytes[2];
43} UINT16BE;
44
45typedef struct UINT32BE
46{
47   UINT8 bytes[4];
48} UINT32BE;
49
50INLINE UINT16 get_UINT16BE(UINT16BE word)
51{
52   return (word.bytes[0] << 8) | word.bytes[1];
53}
54
55INLINE void set_UINT16BE(UINT16BE *word, UINT16 data)
56{
57   word->bytes[0] = (data >> 8) & 0xff;
58   word->bytes[1] = data & 0xff;
59}
60
61INLINE UINT32 get_UINT32BE(UINT32BE word)
62{
63   return (word.bytes[0] << 24) | (word.bytes[1] << 16) | (word.bytes[2] << 8) | word.bytes[3];
64}
65
66INLINE void set_UINT32BE(UINT32BE *word, UINT32 data)
67{
68   word->bytes[0] = (data >> 24) & 0xff;
69   word->bytes[1] = (data >> 16) & 0xff;
70   word->bytes[2] = (data >> 8) & 0xff;
71   word->bytes[3] = data & 0xff;
72}
73
74/*
75   disk image header
76*/
77typedef struct disk_image_header
78{
79   UINT32BE cylinders;         /* number of cylinders on hard disk (big-endian) */
80   UINT32BE heads;            /* number of heads on hard disk (big-endian) */
81   UINT32BE sectors_per_track;   /* number of sectors per track on hard disk (big-endian) */
82   UINT32BE bytes_per_sector;   /* number of bytes of data per sector on hard disk (big-endian) */
83} disk_image_header;
84
85enum
86{
87   header_len = sizeof(disk_image_header)
88};
89
90/*
91   Disk structure:
92
93   Track 0 Sector 0: see below
94   Track 0 Sector 1: list of bad ADU
95   Track 0 Sector 2 through N: disk allocation bitmap
96   Track 1 Sector 0 through N-2: optional disk program image loader
97   Track 1 Sector N-1: copy of Track 0 Sector 0
98   Track 1 Sector N: copy of Track 0 Sector 1
99   Last cylinder has disagnostic information (reported as .S$DIAG)
100   Remaining sectors are used for fdr and data.
101*/
102
103/*
104   SC0 record (Disk sector 0)
105*/
106typedef struct ti990_sc0
107{
108   char      vnm[8];         /* volume name */
109   UINT16BE   tna;         /* total number of ADUs */
110   UINT8      sbm;         /* starting sector of bit maps */
111   UINT8      tbm;         /* total bit maps */
112   UINT16BE   rl;            /* track 01 record length */
113   UINT16BE   slt;         /* system loader track address */
114   UINT8      fill00[6];      /* * * RESERVED * * */
115   UINT16BE   nba;         /* total number of bad ADUs on disk */
116   UINT16BE   sle;         /* system loader entry point */
117   UINT16BE   sll;         /* system loader length */
118   UINT8      fill01[8];      /* * * RESERVED * * */
119   UINT16BE   lt1;         /* system loader track (copy 2) */
120   UINT8      fill02[8];      /* * * RESERVED * * */
121   char      pi1[8];         /* primary system file name */
122   char      pi2[8];         /* secondary system file name */
123   UINT16BE   pif;         /* system selector */
124   UINT16BE   vda;         /* volume directory ADU */
125   UINT16BE   vpl;         /* vcatalog physical record length */
126   UINT16BE   spa;         /* sectors per ADU */
127   UINT8      dcd[4];         /* disk creation date */
128   char      pf1[8];         /* primary program file */
129   char      pf2[8];         /* secondary program file */
130   UINT16BE   pff;         /* program file switch */
131   char      of1[8];         /* primary overlay file */
132   char      of2[8];         /* secondary overlay file */
133   UINT16BE   off;         /* overlay file switch */
134   char      il1[8];         /* primary intermediate loader */
135   char      il2[8];         /* secondary intermediate loader */
136   UINT16BE   ilf;         /* intermediate loader flag */
137   char      din[8];         /* diagnostic file name */
138   UINT16BE   dif;         /* diagnostic flag */
139   UINT16BE   drs;         /* default physical record size "DBUILD DETERMINES DEFAULT PRS" (whatever it means) */
140   UINT16BE   bal;         /* starting sector of bad ADU list */
141   UINT16BE   spr;         /* track 0 sectors per record */
142   char      wf1[8];         /* WCS primary microcode file */
143   char      wf2[8];         /* WCS secondary microcode file */
144   UINT16BE   wff;         /* WCS flag switch */
145   UINT16BE   vif;         /* track 1 select flag (whatever it means) volume information copied flag */
146   UINT16BE   sta;         /* state of disk: */
147                           /*   1 = disk surface has not been tested for defects */
148                           /*   2 = disk surface has been tested, but no file system has been installed */
149                           /*   3 = a file system has been installed */
150   UINT16BE   dct;         /* disk creation time */
151   UINT16BE   fsf;         /* * * RESERVED * * */
152   /* SCOSIZ = >AA */
153} ti990_sc0;
154
155/*
156   DOR (Directory Overhead Record)
157*/
158typedef struct ti990_dor
159{
160   UINT16BE nrc;            /* # records in directory (minus DOR) nrc = nfl + nar (+ tfc???) */
161   UINT16BE nfl;            /* # files currently in directory */
162   UINT16BE nar;            /* # of available records */
163   UINT16BE tfc;            /* number of temporary files */
164   char dnm[8];            /* directory file name (VCATALOG for root) */
165   UINT16BE lvl;            /* level # of directory (0 for root, 1 for children of root, 2 for grandchildren, etc) */
166   char pnm[8];            /* name of parent directory (VCATALOG for root, even though it makes little sense) */
167   UINT16BE prs;            /* "default physical record length (used for file creation)" */
168   /* DORSIZ = >1C */
169} ti990_dor;
170
171/*
172   file flags found in fdr
173*/
174enum
175{
176   ace_flg_rdf = 0x8000,      /* read access flag */
177   ace_flg_wrf = 0x4000,      /* write access flag */
178   ace_flg_dlf = 0x2000,      /* delete access flag */
179   ace_flg_exf = 0x1000,      /* execute access flag */
180   ace_flg_ctf = 0x0800,      /* control access flag */
181
182   fdr_fl1_sec = 0x8000,      /* file secured flag */
183
184   fdr_flg_fu  = 0xc000,      /* file usage bits */
185   fdr_flg_fu_shift  = 14,
186   fdr_flg_fmt = 0x3000,      /* file format bits */
187   fdr_flg_fmt_shift  = 12,
188   fdr_flg_all = 0x0800,      /* extendable file flag */
189   fdr_flg_ft  = 0x0600,      /* file type bits */
190   fdr_flg_ft_shift  = 9,
191   fdr_flg_wpb = 0x0100,      /* write protect bit */
192   fdr_flg_dpb = 0x0080,      /* delete protect bit */
193   fdr_flg_tmp = 0x0040,      /* temporary file flag */
194   fdr_flg_blb = 0x0020,      /* blocked file flag */
195   fdr_flg_ali = 0x0010,      /* alias flag bit */
196   fdr_flg_fwt = 0x0008,      /* forced write / partial logging */
197   fdr_flg_cdr = 0x0001      /* record is CDR */
198};
199
200/*
201   ACE subrecord found in FDR
202*/
203typedef struct ti990_ace
204{
205   char      agn[8];            /* access group name */
206   UINT16BE   flg;            /* flags */
207} ti990_ace;
208
209/*
210   FDR record
211*/
212typedef struct ti990_fdr
213{
214   UINT16BE   hkc;         /* hask key count: the number of file descriptor records that are present in the directory that hashed to this record number */
215   UINT16BE   hkv;         /* hask key value: the result of the hash algorithm for the file name actually covered in this record */
216   char      fnm[8];         /* file name */
217   UINT8      rsv[2];         /* reserved */
218   UINT16BE   fl1;         /* flags word 1 */
219   UINT16BE   flg;         /* flags word 2 */
220   UINT16BE   prs;         /* physical record size */
221   UINT16BE   lrs;         /* logical record size */
222   UINT16BE   pas;         /* primary allocation size: # of ADUs allocated in primary allocation block? */
223   UINT16BE   paa;         /* primary allocation address: first ADU of primary allocation block? */
224   UINT16BE   sas;         /* secondary allocation size: used to determinate the # of blocks allocated per secondary allocation */
225   UINT16BE   saa;         /* offset of secondary table: ???? "offset into this FDR of the secondary allocation table, if any.  No secondary allocation table is denoted by 0.  Secondary allocations are present only for unbounded files." */
226   UINT16BE   rfa;         /* record number of first alias */
227   UINT32BE   eom;         /* end of medium record number */
228   UINT32BE   bkm;         /* end of medium block number */
229   UINT16BE   ofm;         /* end of medium offset / */
230                           /* prelog number for KIF */
231   UINT32BE   fbq;         /* free block queue head */
232   UINT16BE   btr;         /* B-tree roots block # */
233   UINT32BE   ebq;         /* empty block queue head */
234   UINT16BE   kdr;         /* key descriptions record # */
235   UINT8      ud[6];         /* last update date */
236   UINT8      cd[6];         /* creation date */
237   UINT8      apb;         /* ADU's per block */
238   UINT8      bpa;         /* blocks per ADU */
239   UINT16BE   mrs;         /* minimumu KIF record size */
240   UINT8      sat[64];      /* secondary allocation table: 16 2-word entries.  The first word of an entry contains the size, in ADUs, of the secondary allocation.  The second word contains the starting ADU of the allocation. */
241
242/* bytes >86 to >100 are optional */
243   UINT8      res[10];      /* reserved: seem to be actually meaningful (at least under DX10 3.6.x) */
244   char      uid[8];         /* user id of file creator */
245   UINT16BE   psa;         /* public security attribute */
246   ti990_ace   ace[9];         /* 9 access control entries */
247   UINT8      fil[2];         /* not used */
248} ti990_fdr;
249
250/*
251   ADR record: variant of FDR for Aliases
252
253   The fields marked here with *** are in the ADR template to maintain
254   compatability with the FDR template.
255*/
256typedef struct ti990_adr
257{
258   UINT16BE   hkc;         /* hask key count */
259   UINT16BE   hkv;         /* hask key value */
260   char      fnm[8];         /* file name */
261   char      psw[4];         /* "password" (whatever it means) */
262   UINT16BE   flg;         /* flags (same as fdr.flg) */
263   UINT16BE   fill00;         /* *** physical record size */
264   UINT16BE   fill01;         /* *** logical record size */
265   UINT16BE   fill02;         /* *** primary allocation size */
266   UINT16BE   fill03;         /* *** primary allocation address */
267   UINT16BE   fill04;         /* *** secondary allocation size */
268   UINT16BE   fill05;         /* *** secondary allocation address */
269   UINT16BE   rna;         /* record number of next ADR */
270   UINT16BE   raf;         /* record # of actual FDR (from 1 through dor.nrc) */
271} ti990_adr;
272
273/*
274   CDR record: variant of FDR for Channel
275
276   The CDR is the permanent record of a channel.  It is carried as an alias
277   of the program file in which the channel owner task resides.
278*/
279typedef struct ti990_cdr
280{
281   UINT16BE   hkc;         /* hask key count */
282   UINT16BE   hkv;         /* hask key value */
283   char      fnm[8];         /* file name */
284   UINT16BE   fill00;         /* reserved */
285   UINT16BE   fill01;         /* reserved */
286   UINT16BE   fdf;         /* flags (same as fdr.flg) */
287   UINT8      flg;         /* channel flzgs */
288   UINT8      iid;         /* owner task installed ID */
289   UINT8      typ;         /* default resource type */
290   UINT8      tf;            /* resource type flags */
291   UINT16BE   mxl;         /* maximum message length */
292   UINT8      fill04[6];      /* reserved (and, no, I don't know where fill02 and fill03 have gone) */
293   UINT16BE   rna;         /* record number of next CDR or ADR */
294   UINT16BE   raf;         /* record # of actual FDR */
295   UINT8      fill05[110];   /* reserved */
296   char      uid[8];         /* user ID of channel creator */
297   UINT16BE   psa;         /* public security attribute */
298   UINT8      scg[94];      /* "SDT with 9 control groups" (whatever it means - and, no, 94 is not dividable by 9) */
299   UINT8      fill06[8];      /* reserved */
300} ti990_cdr;
301
302/*
303   Based on contents of the flags field, catalog entries may be either an FDR,
304   an ADR or a CDR.
305
306   They may be a KDR, too, but confusion is impossible because the KDR FILL00
307   field starts at offset 4, and therefore if we try to interpret a KDR as an
308   FDR (or ADR, CDR), we will find fnm[0] and assume the FDR is empty.
309*/
310typedef union directory_entry
311{
312   ti990_fdr fdr;
313   ti990_adr adr;
314   ti990_cdr cdr;
315} directory_entry;
316
317#if 0
318
319/*
320   tifile header: stand-alone file
321*/
322typedef struct tifile_header
323{
324   char tifiles[8];      /* always '\7TIFILES' */
325   UINT8 secsused_MSB;      /* file length in sectors (big-endian) */
326   UINT8 secsused_LSB;
327   UINT8 flags;         /* see enum above */
328   UINT8 recspersec;      /* records per sector */
329   UINT8 eof;            /* current position of eof in last sector (0->255)*/
330   UINT8 reclen;         /* bytes per record ([1,255] 0->256) */
331   UINT8 fixrecs_MSB;      /* file length in records (big-endian) */
332   UINT8 fixrecs_LSB;
333   UINT8 res[128-16];      /* reserved */
334} tifile_header;
335
336
337/*
338   catalog entry (used for in-memory catalog)
339*/
340typedef struct catalog_entry
341{
342   UINT16 fdr_secnum;
343   char filename[10];
344} catalog_entry;
345
346#endif
347
348/*
349   Disk geometry
350*/
351typedef struct ti990_geometry
352{
353   unsigned int cylinders, heads, sectors_per_track, bytes_per_sector;
354} ti990_geometry;
355
356/*
357   Physical sector address
358*/
359typedef struct ti990_phys_sec_address
360{
361   int cylinder;
362   int head;
363   int sector;
364} ti990_phys_sec_address;
365
366/*
367   ti99 disk image descriptor
368*/
369typedef struct ti990_image
370{
371   imgtool_stream *file_handle;      /* imgtool file handle */
372   ti990_geometry geometry;   /* geometry */
373   ti990_sc0 sec0;            /* cached copy of sector 0 */
374} ti990_image;
375
376/*
377   ti990 catalog iterator, used when imgtool reads the catalog
378*/
379typedef struct ti990_iterator
380{
381   ti990_image *image;
382   int level;                     /* current recursion level */
383   int nrc[MAX_DIR_LEVEL];            /* length of disk catalogs in records */
384   int index[MAX_DIR_LEVEL];         /* current index in the disk catalog */
385   directory_entry xdr[MAX_DIR_LEVEL];   /* fdr records */
386} ti990_iterator;
387
388
389static imgtoolerr_t ti990_image_init(imgtool_image *img, imgtool_stream *f);
390static void ti990_image_exit(imgtool_image *img);
391static void ti990_image_info(imgtool_image *img, char *string, size_t len);
392static imgtoolerr_t ti990_image_beginenum(imgtool_directory *enumeration, const char *path);
393static imgtoolerr_t ti990_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
394static void ti990_image_closeenum(imgtool_directory *enumeration);
395static imgtoolerr_t ti990_image_freespace(imgtool_partition *partition, UINT64 *size);
396#ifdef UNUSED_FUNCTION
397static imgtoolerr_t ti990_image_readfile(imgtool_partition *partition, const char *fpath, imgtool_stream *destf);
398static imgtoolerr_t ti990_image_writefile(imgtool_partition *partition, const char *fpath, imgtool_stream *sourcef, option_resolution *writeoptions);
399static imgtoolerr_t ti990_image_deletefile(imgtool_partition *partition, const char *fpath);
400#endif
401static imgtoolerr_t ti990_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions);
402
403enum
404{
405   /*ti990_createopts_volname = 'A',*/
406   ti990_createopts_cylinders = 'B',
407   ti990_createopts_heads = 'C',
408   ti990_createopts_sectors = 'D',
409   ti990_createopts_sectorsize = 'E'
410};
411
412OPTION_GUIDE_START( ti990_create_optionguide )
413   /*OPTION_STRING(ti990_createopts_volname, "label",   "Volume name" )*/
414   OPTION_INT(ti990_createopts_cylinders, "cylinders", "Cylinders" )
415   OPTION_INT(ti990_createopts_heads, "heads", "Heads" )
416   OPTION_INT(ti990_createopts_sectors, "sectors", "Sectors" )
417   OPTION_INT(ti990_createopts_sectorsize, "bytes per sector (typically 256)", "Bytes Per Sector" )
418OPTION_GUIDE_END
419
420#define symb2str2(a) #a
421#define symb2str(a) symb2str2(a)
422#define ti990_create_optionspecs "B1-[145]-"symb2str(MAX_CYLINDERS)";C1-[4]-"symb2str(MAX_HEADS)";D1-[32]-"symb2str(MAX_SECTORS_PER_TRACK)";E"symb2str(MIN_SECTOR_SIZE)"-[256]-"symb2str(MAX_SECTOR_SIZE)";"
423
424void ti990_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
425{
426   switch(state)
427   {
428      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "ti990hd"); break;
429      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "TI990 Hard Disk"); break;
430      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "hd"); break;
431      case IMGTOOLINFO_STR_EOLN:                     /* strcpy(info->s = imgtool_temp_str(), "\r"); */ break;
432
433      case IMGTOOLINFO_PTR_OPEN:                     info->open = ti990_image_init; break;
434      case IMGTOOLINFO_PTR_CLOSE:                     info->close = ti990_image_exit; break;
435      case IMGTOOLINFO_PTR_INFO:                     info->info = ti990_image_info; break;
436      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = ti990_image_beginenum; break;
437      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = ti990_image_nextenum; break;
438      case IMGTOOLINFO_PTR_CLOSE_ENUM:               info->close_enum = ti990_image_closeenum; break;
439      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = ti990_image_freespace; break;
440      case IMGTOOLINFO_PTR_READ_FILE:                  /* info->read_file = ti990_image_readfile; */ break;
441      case IMGTOOLINFO_PTR_WRITE_FILE:               /* info->write_file = ti990_image_writefile; */ break;
442      case IMGTOOLINFO_PTR_DELETE_FILE:               /* info->delete_file = ti990_image_deletefile; */ break;
443      case IMGTOOLINFO_PTR_CREATE:                  info->create = ti990_image_create; break;
444
445      case IMGTOOLINFO_PTR_CREATEIMAGE_OPTGUIDE:         info->createimage_optguide = ti990_create_optionguide; break;
446      case IMGTOOLINFO_STR_CREATEIMAGE_OPTSPEC:         strcpy(info->s = imgtool_temp_str(), ti990_create_optionspecs); break;
447   }
448}
449
450#ifdef UNUSED_FUNCTION
451/*
452   Convert a C string to a 8-character file name (padded with spaces if necessary)
453*/
454static void str_to_fname(char dst[8], const char *src)
455{
456   int i;
457
458
459   i = 0;
460
461   /* copy 8 characters at most */
462   if (src)
463      while ((i<8) && (src[i]!='\0'))
464      {
465         dst[i] = src[i];
466         i++;
467      }
468
469   /* pad with spaces */
470   while (i<8)
471   {
472      dst[i] = ' ';
473      i++;
474   }
475}
476#endif
477
478/*
479   Convert a 8-character file name to a C string (removing trailing spaces if necessary)
480*/
481static void fname_to_str(char *dst, const char src[8], int n)
482{
483   int i;
484   int last_nonspace;
485
486
487   /* copy 8 characters at most */
488   if (--n > 8)
489      n = 8;
490
491   /* copy filename */
492   i = 0;
493   last_nonspace = -1;
494
495   while (i<n)
496   {
497      dst[i] = src[i];
498      if (src[i] != ' ')
499         last_nonspace = i;
500      i++;
501   }
502
503   /* terminate with '\0' */
504   dst[last_nonspace+1] = '\0';
505}
506
507#if 0
508#pragma mark -
509#pragma mark DISK ROUTINES
510#endif
511
512/*
513   Convert physical sector address to offset
514*/
515static unsigned phys_address_to_offset(const ti990_phys_sec_address *address, const ti990_geometry *geometry)
516{
517   unsigned offset;
518
519   /* current MESS format */
520   offset = (((address->cylinder*geometry->heads) + address->head)*geometry->sectors_per_track + address->sector)*geometry->bytes_per_sector + header_len;
521
522   return offset;
523}
524
525/*
526   Read one sector from a disk image
527
528   file_handle: imgtool file handle
529   address: physical sector address
530   geometry: disk geometry (sectors per track, tracks per side, sides)
531   dest: pointer to destination buffer
532   len: lenght of data to read
533*/
534static int read_sector_physical_len(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, void *dest, int len)
535{
536   int reply;
537
538   if (len > geometry->bytes_per_sector)
539      return 1;
540
541   /* seek to sector */
542   reply = stream_seek(file_handle, phys_address_to_offset(address, geometry), SEEK_SET);
543   if (reply)
544      return 1;
545   /* read it */
546   reply = stream_read(file_handle, dest, len);
547   if (reply != len)
548      return 1;
549
550   return 0;
551}
552
553#ifdef UNUSED_FUNCTION
554/*
555   Read one sector from a disk image
556
557   file_handle: imgtool file handle
558   address: physical sector address
559   geometry: disk geometry (sectors per track, tracks per side, sides)
560   dest: pointer to a destination buffer of geometry->bytes_per_sector bytes
561*/
562static int read_sector_physical(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, void *dest)
563{
564   return read_sector_physical_len(file_handle, address, geometry, dest, geometry->bytes_per_sector);
565}
566#endif
567
568/*
569   Write one sector to a disk image
570
571   file_handle: imgtool file handle
572   address: physical sector address
573   geometry: disk geometry (sectors per track, tracks per side, sides)
574   src: pointer to source buffer
575   len: lenght of source buffer
576*/
577static int write_sector_physical_len(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, const void *src, int len)
578{
579   int reply;
580
581   if (len > geometry->bytes_per_sector)
582      return 1;
583
584   /* seek to sector */
585   reply = stream_seek(file_handle, phys_address_to_offset(address, geometry), SEEK_SET);
586   if (reply)
587      return 1;
588   /* write it */
589   reply = stream_write(file_handle, src, len);
590   if (reply != len)
591      return 1;
592   /* pad with 0s if needed */
593   if (len < geometry->bytes_per_sector)
594   {
595      reply = stream_fill(file_handle, 0, geometry->bytes_per_sector - len);
596
597      if (reply != geometry->bytes_per_sector - len)
598         return 1;
599   }
600
601   return 0;
602}
603
604#ifdef UNUSED_FUNCTION
605/*
606   Write one sector to a disk image
607
608   file_handle: imgtool file handle
609   address: physical sector address
610   geometry: disk geometry (sectors per track, tracks per side, sides)
611   dest: pointer to a source buffer of geometry->bytes_per_sector bytes
612*/
613static int write_sector_physical(imgtool_stream *file_handle, const ti990_phys_sec_address *address, const ti990_geometry *geometry, const void *src)
614{
615   return write_sector_physical_len(file_handle, address, geometry, src, geometry->bytes_per_sector);
616}
617#endif
618
619/*
620   Convert logical sector address to physical sector address
621*/
622static void log_address_to_phys_address(int secnum, const ti990_geometry *geometry, ti990_phys_sec_address *address)
623{
624   address->sector = secnum % geometry->sectors_per_track;
625   secnum /= geometry->sectors_per_track;
626   address->head = secnum % geometry->heads;
627   address->cylinder = secnum / geometry->heads;
628}
629
630/*
631   Read one sector from a disk image
632
633   file_handle: imgtool file handle
634   secnum: logical sector address
635   geometry: disk geometry (sectors per track, tracks per side, sides)
636   dest: pointer to destination buffer
637   len: lenght of data to read
638*/
639static int read_sector_logical_len(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, void *dest, int len)
640{
641   ti990_phys_sec_address address;
642
643
644   log_address_to_phys_address(secnum, geometry, &address);
645
646   return read_sector_physical_len(file_handle, &address, geometry, dest, len);
647}
648
649#ifdef UNUSED_FUNCTION
650/*
651   Read one sector from a disk image
652
653   file_handle: imgtool file handle
654   secnum: logical sector address
655   geometry: disk geometry (sectors per track, tracks per side, sides)
656   dest: pointer to a destination buffer of geometry->bytes_per_sector bytes
657*/
658static int read_sector_logical(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, void *dest)
659{
660   return read_sector_logical_len(file_handle, secnum, geometry, dest, geometry->bytes_per_sector);
661}
662#endif
663
664/*
665   Write one sector to a disk image
666
667   file_handle: imgtool file handle
668   secnum: logical sector address
669   geometry: disk geometry (sectors per track, tracks per side, sides)
670   src: pointer to source buffer
671   len: lenght of source buffer
672*/
673static int write_sector_logical_len(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, const void *src, int len)
674{
675   ti990_phys_sec_address address;
676
677
678   log_address_to_phys_address(secnum, geometry, &address);
679
680   return write_sector_physical_len(file_handle, &address, geometry, src, len);
681}
682
683/*
684   Write one sector to a disk image
685
686   file_handle: imgtool file handle
687   secnum: logical sector address
688   geometry: disk geometry (sectors per track, tracks per side, sides)
689   dest: pointer to a source buffer of geometry->bytes_per_sector bytes
690*/
691static int write_sector_logical(imgtool_stream *file_handle, int secnum, const ti990_geometry *geometry, const void *src)
692{
693   return write_sector_logical_len(file_handle, secnum, geometry, src, geometry->bytes_per_sector);
694}
695
696#if 0
697#pragma mark -
698#pragma mark CATALOG FILE ROUTINES
699#endif
700
701#ifdef UNUSED_FUNCTION
702/*
703   Find the catalog entry and fdr record associated with a file name
704
705   image: ti990_image image record
706   fpath: path of the file to search
707   fdr: pointer to buffer where the fdr record should be stored (may be NULL)
708   catalog_index: on output, index of file catalog entry (may be NULL)
709   out_fdr_secnum: on output, sector address of the fdr (may be NULL)
710   out_parent_fdr_secnum: on output, sector offset of the fdr for the parent
711      directory fdr (-1 if root) (may be NULL)
712*/
713static int find_fdr(ti990_image *image, const char fpath[MAX_PATH_LEN+1], int *catalog_index, int *out_fdr_secnum, int *out_parent_fdr_secnum)
714{
715   int fdr_secnum = -1, parent_fdr_secnum;
716   int i;
717   const char *element_start, *element_end;
718   int element_len;
719   char element[8];
720   ti990_dor dor;
721   directory_entry xdr;
722   int hash_key;
723   int nrc;
724   unsigned base;
725   int reply;
726   int flag;
727
728
729   base = (unsigned) get_UINT16BE(image->sec0.vda) * get_UINT16BE(image->sec0.spa);
730
731   element_start = fpath;
732   do
733   {
734      /* read directory header */
735      reply = read_sector_logical_len(image->file_handle, base, & image->geometry, &dor, sizeof(dor));
736      if (reply)
737         return IMGTOOLERR_READERROR;
738
739      nrc = get_UINT16BE(dor.nrc);
740
741      /* find next path element */
742      element_end = strchr(element_start, '.');
743      element_len = element_end ? (element_end - element_start) : strlen(element_start);
744      if ((element_len > 8) || (element_len == 0))
745         return IMGTOOLERR_BADFILENAME;
746      /* generate file name and hash key */
747      hash_key = 1;
748      for (i=0; i<element_len; i++)
749      {
750         element[i] = element_start[i];
751         hash_key = ((hash_key * (unsigned char) element_start[i]) % nrc) + 1;
752      }
753      while (i<8)
754      {
755         element[i] = ' ';
756         i++;
757      }
758
759      /* search entry in directory */
760      i = hash_key;
761      while (1)
762      {
763         reply = read_sector_logical_len(image->file_handle, base + i, & image->geometry,
764                                    & xdr, 0x86);
765         if (reply)
766            return IMGTOOLERR_READERROR;
767         if (!memcmp(element, xdr.fdr.fnm, 8))
768         {   /* found match !!! */
769            parent_fdr_secnum = fdr_secnum;
770            fdr_secnum = base + i;
771            break;
772         }
773
774         /* next record */
775         if (i != nrc)
776            i++;
777         else
778            i = 1;
779
780         /* exit if we have tested every record */
781         if (i == hash_key)
782            return IMGTOOLERR_FILENOTFOUND;
783      }
784
785      /* iterate */
786      if (element_end)
787      {
788         element_start = element_end+1;
789         /* we need to check that this is a directory */
790         /* if it is an alias to a directory, we need to follow it, too. */
791
792         /* parse flags */
793         flag = get_UINT16BE(xdr.fdr.flg);
794
795         if (flag & fdr_flg_ali)
796         {
797            /* read original fdr */
798            reply = read_sector_logical_len(image->file_handle, base + get_UINT16BE(xdr.adr.raf),
799                                       & image->geometry, & xdr, 0x86);
800
801            flag = get_UINT16BE(xdr.fdr.flg);
802         }
803
804         if (flag & fdr_flg_cdr)
805            /* This is a channel, not a file */
806            return IMGTOOLERR_BADFILENAME;
807         else if (flag & fdr_flg_ali)
808            /* WTH??? */
809            return IMGTOOLERR_CORRUPTIMAGE;
810         else if (((flag >> fdr_flg_fu_shift) & 3) != 1)
811         {
812            /* This file is not a directory */
813            return IMGTOOLERR_BADFILENAME;
814         }
815
816         /* initialize base */
817         base = (unsigned) get_UINT16BE(xdr.fdr.paa) * get_UINT16BE(image->sec0.spa);
818      }
819      else
820         element_start = NULL;
821   }
822   while (element_start);
823
824   if (catalog_index)
825      *catalog_index = i;
826
827   if (out_fdr_secnum)
828      *out_fdr_secnum = fdr_secnum;
829
830   if (out_parent_fdr_secnum)
831      *out_parent_fdr_secnum = parent_fdr_secnum;
832
833   return 0;
834}
835#endif
836
837#if 0
838/*
839   Allocate one sector on disk, for use as a fdr record
840
841   image: ti99_image image record
842   fdr_secnum: on output, logical address of a free sector
843*/
844static int alloc_fdr_sector(ti99_image *image, int *fdr_secnum)
845{
846   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
847   int i;
848
849
850   for (i=0; i<totsecs; i++)
851   {
852      if (! (image->sec0.abm[i >> 3] & (1 << (i & 7))))
853      {
854         *fdr_secnum = i;
855         image->sec0.abm[i >> 3] |= 1 << (i & 7);
856
857         return 0;
858      }
859   }
860
861   return IMGTOOLERR_NOSPACE;
862}
863
864/*
865   Extend a file with nb_alloc_sectors extra sectors
866
867   image: ti99_image image record
868   fdr: file fdr record
869   nb_alloc_sectors: number of sectors to allocate
870*/
871static int alloc_file_sectors(ti99_image *image, ti99_fdr *fdr, int nb_alloc_sectors)
872{
873   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
874   int free_sectors;
875   int secsused;
876   int i;
877   int lnks_index;
878   int cur_sec, last_sec, p_last_sec;
879   int cur_block_len, cur_block_start;
880   int first_best_block_len, first_best_block_start = 0;
881   int second_best_block_len, second_best_block_start = 0;
882   int search_start;
883
884   /* compute free space */
885   free_sectors = 0;
886   for (i=0; i<totsecs; i++)
887   {
888      if (! (image->sec0.abm[i >> 3] & (1 << (i & 7))))
889         free_sectors++;
890   }
891
892   /* check we have enough free space */
893   if (free_sectors < nb_alloc_sectors)
894      return IMGTOOLERR_NOSPACE;
895
896   /* current number of data sectors in file */
897   secsused = get_fdr_secsused(fdr);
898
899   if (secsused == 0)
900   {   /* links array must be empty */
901      lnks_index = 0;
902   }
903   else
904   {   /* try to extend last block */
905      last_sec = -1;
906      for (lnks_index=0; lnks_index<76; lnks_index++)
907      {
908         p_last_sec = last_sec;
909         last_sec = (fdr->lnks[lnks_index][2] << 4) | (fdr->lnks[lnks_index][1] >> 4);
910         if (last_sec >= (secsused-1))
911            break;
912      }
913      if (lnks_index == 76)
914         /* that sucks */
915         return IMGTOOLERR_CORRUPTIMAGE;
916
917      if (last_sec > (secsused-1))
918      {   /* some extra space has already been allocated */
919         cur_block_len = last_sec - (secsused-1);
920         if (cur_block_len > nb_alloc_sectors)
921            cur_block_len = nb_alloc_sectors;
922
923         secsused += cur_block_len;
924         set_fdr_secsused(fdr, secsused);
925         nb_alloc_sectors -= cur_block_len;
926         if (! nb_alloc_sectors)
927            return 0;   /* done */
928      }
929
930      /* block base */
931      cur_sec = ((fdr->lnks[lnks_index][1] & 0xf) << 8) | fdr->lnks[lnks_index][0];
932      /* point past block end */
933      cur_sec += last_sec-p_last_sec;
934      /* count free sectors after last block */
935      cur_block_len = 0;
936      for (i=cur_sec; (! (image->sec0.abm[i >> 3] & (1 << (i & 7)))) && (cur_block_len < nb_alloc_sectors) && (i < totsecs); i++)
937         cur_block_len++;
938      if (cur_block_len)
939      {   /* extend last block */
940         secsused += cur_block_len;
941         set_fdr_secsused(fdr, secsused);
942         last_sec += cur_block_len;
943         nb_alloc_sectors -= cur_block_len;
944         fdr->lnks[lnks_index][1] = (fdr->lnks[lnks_index][1] & 0x0f) | (last_sec << 4);
945         fdr->lnks[lnks_index][2] = last_sec >> 4;
946         for (i=0; i<cur_block_len; i++)
947            image->sec0.abm[(i+cur_sec) >> 3] |= 1 << ((i+cur_sec) & 7);
948         if (! nb_alloc_sectors)
949            return 0;   /* done */
950      }
951      lnks_index++;
952      if (lnks_index == 76)
953         /* that sucks */
954         return IMGTOOLERR_NOSPACE;
955   }
956
957   search_start = image->data_offset;   /* initially, search for free space only in data space */
958   while (nb_alloc_sectors)
959   {
960      /* find smallest data block at least nb_alloc_sectors in lenght, and largest data block less than nb_alloc_sectors in lenght */
961      first_best_block_len = INT_MAX;
962      second_best_block_len = 0;
963      for (i=search_start; i<totsecs; i++)
964      {
965         if (! (image->sec0.abm[i >> 3] & (1 << (i & 7))))
966         {   /* found one free block */
967            /* compute its lenght */
968            cur_block_start = i;
969            cur_block_len = 0;
970            while ((i<totsecs) && (! (image->sec0.abm[i >> 3] & (1 << (i & 7)))))
971            {
972               cur_block_len++;
973               i++;
974            }
975            /* compare to previous best and second-best blocks */
976            if ((cur_block_len < first_best_block_len) && (cur_block_len >= nb_alloc_sectors))
977            {
978               first_best_block_start = cur_block_start;
979               first_best_block_len = cur_block_len;
980               if (cur_block_len == nb_alloc_sectors)
981                  /* no need to search further */
982                  break;
983            }
984            else if ((cur_block_len > second_best_block_len) && (cur_block_len < nb_alloc_sectors))
985            {
986               second_best_block_start = cur_block_start;
987               second_best_block_len = cur_block_len;
988            }
989         }
990      }
991
992      if (first_best_block_len != INT_MAX)
993      {   /* found one contiguous block which can hold it all */
994         secsused += nb_alloc_sectors;
995         set_fdr_secsused(fdr, secsused);
996
997         fdr->lnks[lnks_index][0] = first_best_block_start;
998         fdr->lnks[lnks_index][1] = ((first_best_block_start >> 8) & 0x0f) | ((secsused-1) << 4);
999         fdr->lnks[lnks_index][2] = (secsused-1) >> 4;
1000         for (i=0; i<nb_alloc_sectors; i++)
1001            image->sec0.abm[(i+first_best_block_start) >> 3] |= 1 << ((i+first_best_block_start) & 7);
1002
1003         nb_alloc_sectors = 0;
1004      }
1005      else if (second_best_block_len != 0)
1006      {   /* jeez, we need to fragment it.  We use the largest smaller block to limit fragmentation. */
1007         secsused += second_best_block_len;
1008         set_fdr_secsused(fdr, secsused);
1009
1010         fdr->lnks[lnks_index][0] = second_best_block_start;
1011         fdr->lnks[lnks_index][1] = ((second_best_block_start >> 8) & 0x0f) | ((secsused-1) << 4);
1012         fdr->lnks[lnks_index][2] = (secsused-1) >> 4;
1013         for (i=0; i<second_best_block_len; i++)
1014            image->sec0.abm[(i+second_best_block_start) >> 3] |= 1 << ((i+second_best_block_start) & 7);
1015
1016         nb_alloc_sectors -= second_best_block_len;
1017
1018         lnks_index++;
1019         if (lnks_index == 76)
1020            /* that sucks */
1021            return IMGTOOLERR_NOSPACE;
1022      }
1023      else if (search_start != 0)
1024      {   /* we did not find any free sector in the data section of the disk */
1025         search_start = 0;   /* time to fall back to fdr space */
1026      }
1027      else
1028         return IMGTOOLERR_NOSPACE;   /* This should never happen, as we pre-check that there is enough free space */
1029   }
1030
1031   return 0;
1032}
1033
1034/*
1035   Allocate a new (empty) file
1036*/
1037static int new_file(ti99_image *image, char filename[10], int *out_fdr_secnum/*, ti99_fdr *fdr,*/)
1038{
1039   int fdr_secnum;
1040   int catalog_index, i;
1041   int reply = 0;
1042
1043
1044   /* find insertion point in catalog */
1045   i = 0;
1046   if ((image->catalog[0].fdr_secnum == 0) && (image->catalog[1].fdr_secnum != 0))
1047      i = 1;   /* skip empty entry 0 (it must be a non-listable catalog) */
1048
1049   for (; (i<128) && ((fdr_secnum = image->catalog[i].fdr_secnum) != 0) && ((reply = memcmp(image->catalog[i].filename, filename, 10)) < 0); i++)
1050      ;
1051
1052   if (i == 128)
1053      /* catalog is full */
1054      return IMGTOOLERR_NOSPACE;
1055   else if (fdr_secnum && (reply == 0))
1056      /* file already exists */
1057      return IMGTOOLERR_BADFILENAME;
1058   else
1059   {
1060      catalog_index = i;
1061      reply = alloc_fdr_sector(image, &fdr_secnum);
1062      if (reply)
1063         return reply;
1064
1065      /* look for first free entry in catalog */
1066      for (i=catalog_index; image->catalog[i].fdr_secnum != 0; i++)
1067         ;
1068
1069      if (i == 128)
1070         /* catalog is full */
1071            return IMGTOOLERR_NOSPACE;
1072
1073      /* shift catalog entries until the insertion point */
1074      for (/*i=127*/; i>catalog_index; i--)
1075         image->catalog[i] = image->catalog[i-1];
1076
1077      /* write new catalog entry */
1078      image->catalog[catalog_index].fdr_secnum = fdr_secnum;
1079      memcpy(image->catalog[catalog_index].filename, filename, 10);
1080      if (out_fdr_secnum)
1081         *out_fdr_secnum = fdr_secnum;
1082   }
1083
1084   return 0;
1085}
1086
1087/*
1088   Compare two (possibly empty) catalog entry for qsort
1089*/
1090static int qsort_catalog_compare(const void *p1, const void *p2)
1091{
1092   const catalog_entry *entry1 = p1;
1093   const catalog_entry *entry2 = p2;
1094
1095   if ((entry1->fdr_secnum == 0) && (entry2->fdr_secnum == 0))
1096      return 0;
1097   else if (entry1->fdr_secnum == 0)
1098      return +1;
1099   else if (entry2->fdr_secnum == 0)
1100      return -1;
1101   else
1102      return memcmp(entry1->filename, entry2->filename, 10);
1103}
1104#endif
1105
1106/*
1107   Open a file as a ti990_image.
1108*/
1109static imgtoolerr_t ti990_image_init(imgtool_image *img, imgtool_stream *f)
1110{
1111   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1112   disk_image_header header;
1113   int reply;
1114   unsigned totsecs;
1115
1116   image->file_handle = f;
1117   reply = stream_read(f, &header, sizeof(header));
1118   if (reply != sizeof(header))
1119      return IMGTOOLERR_READERROR;
1120
1121   image->geometry.cylinders = get_UINT32BE(header.cylinders);
1122   image->geometry.heads = get_UINT32BE(header.heads);
1123   image->geometry.sectors_per_track = get_UINT32BE(header.sectors_per_track);
1124   image->geometry.bytes_per_sector = get_UINT32BE(header.bytes_per_sector);
1125
1126   totsecs = image->geometry.cylinders*image->geometry.heads*image->geometry.sectors_per_track;
1127
1128   if ((image->geometry.bytes_per_sector < MIN_SECTOR_SIZE)
1129      || (image->geometry.bytes_per_sector > MAX_SECTOR_SIZE)
1130      || (image->geometry.sectors_per_track > MAX_SECTORS_PER_TRACK)
1131      || (image->geometry.heads > MAX_HEADS)
1132      || (image->geometry.cylinders > MAX_CYLINDERS)
1133      || (totsecs < 1)
1134      || (stream_size(f) != header_len + totsecs*image->geometry.bytes_per_sector))
1135   {
1136      return IMGTOOLERR_CORRUPTIMAGE;
1137   }
1138
1139   {
1140      ti990_phys_sec_address address = { 0, 0, 0 };
1141      reply = read_sector_physical_len(f, &address, &image->geometry, & image->sec0, sizeof(image->sec0));
1142   }
1143   if (reply)
1144   {
1145      return IMGTOOLERR_READERROR;
1146   }
1147
1148   if ((get_UINT16BE(image->sec0.tna)*get_UINT16BE(image->sec0.spa) > totsecs)
1149      || ((get_UINT16BE(image->sec0.spa) != 1) && (get_UINT16BE(image->sec0.spa) % 3)))
1150   {
1151      return IMGTOOLERR_CORRUPTIMAGE;
1152   }
1153
1154   if ((get_UINT16BE(image->sec0.vpl) != 0x86) && (get_UINT16BE(image->sec0.vpl) != 0x100))
1155   {
1156      return IMGTOOLERR_CORRUPTIMAGE;
1157   }
1158
1159   return IMGTOOLERR_SUCCESS;
1160}
1161
1162/*
1163   close a ti990_image
1164*/
1165static void ti990_image_exit(imgtool_image *img)
1166{
1167   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1168   stream_close(image->file_handle);
1169}
1170
1171/*
1172   get basic information on a ti990_image
1173
1174   Currently returns the volume name
1175*/
1176static void ti990_image_info(imgtool_image *img, char *string, size_t len)
1177{
1178   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1179   char vol_name[9];
1180
1181   fname_to_str(vol_name, image->sec0.vnm, 9);
1182
1183   snprintf(string, len, "%s", vol_name);
1184}
1185
1186/*
1187   Open the disk catalog for enumeration
1188*/
1189static imgtoolerr_t ti990_image_beginenum(imgtool_directory *enumeration, const char *path)
1190{
1191   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
1192   ti990_iterator *iter = (ti990_iterator *) imgtool_directory_extrabytes(enumeration);
1193   ti990_dor dor;
1194   int reply;
1195
1196   iter->image = image;
1197
1198   reply = read_sector_logical_len(iter->image->file_handle,
1199                           (unsigned) get_UINT16BE(iter->image->sec0.vda) * get_UINT16BE(iter->image->sec0.spa),
1200                           & iter->image->geometry, &dor, sizeof(dor));
1201
1202   if (reply)
1203      return IMGTOOLERR_READERROR;
1204
1205   iter->level = 0;
1206   iter->nrc[0] = get_UINT16BE(dor.nrc);
1207   iter->index[0] = 0;
1208
1209   return IMGTOOLERR_SUCCESS;
1210}
1211
1212/*
1213   Enumerate disk catalog next entry
1214*/
1215static imgtoolerr_t ti990_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
1216{
1217   ti990_iterator *iter = (ti990_iterator *) imgtool_directory_extrabytes(enumeration);
1218   int flag;
1219   int reply = 0;
1220
1221
1222   ent->corrupt = 0;
1223   ent->eof = 0;
1224
1225   while ((iter->level >= 0)
1226         && (! (reply = read_sector_logical_len(iter->image->file_handle,
1227                                       iter->level ? (unsigned) get_UINT16BE(iter->xdr[iter->level-1].fdr.paa) * get_UINT16BE(iter->image->sec0.spa) + (iter->index[iter->level]+1)
1228                                                : (unsigned) get_UINT16BE(iter->image->sec0.vda) * get_UINT16BE(iter->image->sec0.spa) + (iter->index[iter->level]+1),
1229                                       & iter->image->geometry, &iter->xdr[iter->level],
1230                                       iter->level ? get_UINT16BE(iter->xdr[iter->level-1].fdr.prs)
1231                                                : get_UINT16BE(iter->image->sec0.vpl))))
1232         && (iter->xdr[iter->level].fdr.fnm[0] == 0))
1233   {
1234      iter->index[iter->level]++;
1235      while (iter->index[iter->level] >= iter->nrc[iter->level])
1236         iter->level--;
1237   }
1238
1239   if (iter->level < 0)
1240   {
1241      ent->eof = 1;
1242   }
1243   else if (reply)
1244      return IMGTOOLERR_READERROR;
1245   else
1246   {
1247#if 0
1248      fname_to_str(ent->filename, iter->xdr[iter->level].fdr.fnm, sizeof(ent->filename) / sizeof(ent->filename[0]));
1249#else
1250      {
1251         int i;
1252         char buf[9];
1253
1254         ent->filename[0] = '\0';
1255         for (i=0; i<iter->level; i++)
1256         {
1257            fname_to_str(buf, iter->xdr[i].fdr.fnm, 9);
1258            strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
1259            strncat(ent->filename, ".", sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
1260         }
1261         fname_to_str(buf, iter->xdr[iter->level].fdr.fnm, 9);
1262         strncat(ent->filename, buf, sizeof(ent->filename) / sizeof(ent->filename[0]) - 1);
1263      }
1264#endif
1265
1266      /* parse flags */
1267      flag = get_UINT16BE(iter->xdr[iter->level].fdr.flg);
1268      if (flag & fdr_flg_cdr)
1269      {
1270         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "CHANNEL");
1271
1272         ent->filesize = 0;
1273      }
1274      else if (flag & fdr_flg_ali)
1275      {
1276         ti990_fdr target_fdr;
1277         char buf[9];
1278
1279         reply = read_sector_logical_len(iter->image->file_handle,
1280                                    iter->level ? ((unsigned) get_UINT16BE(iter->xdr[iter->level-1].fdr.paa) * get_UINT16BE(iter->image->sec0.spa) + get_UINT16BE(iter->xdr[iter->level].adr.raf))
1281                                             : ((unsigned) get_UINT16BE(iter->image->sec0.vda) * get_UINT16BE(iter->image->sec0.spa) + get_UINT16BE(iter->xdr[iter->level].adr.raf)),
1282                                    & iter->image->geometry, &target_fdr,
1283                                    iter->level ? get_UINT16BE(iter->xdr[iter->level-1].fdr.prs)
1284                                             : get_UINT16BE(iter->image->sec0.vpl));
1285
1286         fname_to_str(buf, target_fdr.fnm, 9);
1287
1288         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "ALIAS OF %s", buf);
1289
1290         ent->filesize = 0;
1291      }
1292      else
1293      {
1294         const char *fmt, *type;
1295
1296         switch ((flag >> fdr_flg_fmt_shift) & 3)
1297         {
1298         case 0:
1299            fmt = "NBS";
1300            break;
1301         case 1:
1302            fmt = "BS ";
1303            break;
1304         default:
1305            fmt = "???";
1306            break;
1307         }
1308
1309         switch ((flag >> fdr_flg_fu_shift) & 3)
1310         {
1311         case 1:
1312            type = "DIR";
1313            break;
1314         case 2:
1315            type = "PRO";
1316            break;
1317         case 3:
1318            type = "IMG";
1319            break;
1320         default:
1321            switch ((flag >> fdr_flg_ft_shift) & 3)
1322            {
1323            case 1:
1324               type = "SEQ";
1325               break;
1326            case 2:
1327               type = "REL";
1328               break;
1329            case 3:
1330               type = "KIF";
1331               break;
1332            default:
1333               type = "???";
1334               break;
1335            }
1336            break;
1337         }
1338         snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]),
1339                  "%s %c %s%s%s%s%s", fmt, (flag & fdr_flg_all) ? 'N' : 'C', type,
1340                     (flag & fdr_flg_blb) ? "" : " BLK",
1341                     (flag & fdr_flg_tmp) ? " TMP" : "",
1342                     (flag & fdr_flg_wpb) ? " WPT" : "",
1343                     (flag & fdr_flg_dpb) ? " DPT" : "");
1344
1345         /* len in blocks */
1346         ent->filesize = get_UINT32BE(iter->xdr[iter->level].fdr.bkm);
1347         if ((((flag >> fdr_flg_ft_shift) & 3) == 3) || get_UINT16BE(iter->xdr[iter->level].fdr.ofm))
1348            ent->filesize++;
1349
1350         /* convert to ADUs */
1351         if (iter->xdr[iter->level].fdr.apb > 1)
1352            /* more than one ADU per block */
1353            ent->filesize *= iter->xdr[iter->level].fdr.apb;
1354         else if (iter->xdr[iter->level].fdr.bpa > 1)
1355            /* more than one block per ADU */
1356            ent->filesize = (ent->filesize + iter->xdr[iter->level].fdr.bpa - 1) / iter->xdr[iter->level].fdr.bpa;
1357      }
1358      iter->index[iter->level]++;
1359
1360      if (get_UINT16BE(iter->xdr[iter->level].fdr.saa) != 0)
1361         printf("roupoupou");
1362      else
1363      {
1364         int i;
1365         for (i=0; i<64; i++)
1366            if (iter->xdr[iter->level].fdr.sat[i])
1367            {
1368               printf("roupoupou");
1369               break;
1370            }
1371      }
1372
1373      /* recurse subdirectory if applicable */
1374      if ((((flag >> fdr_flg_fu_shift) & 3) == 1)
1375         && (! (flag & fdr_flg_ali))
1376         && (! (flag & fdr_flg_cdr))
1377         && (iter->level < MAX_DIR_LEVEL)
1378         && ! ((iter->level == 0) && ! memcmp(iter->xdr[iter->level].fdr.fnm, "VCATALOG", 8)))
1379      {
1380         ti990_dor dor;
1381
1382         if (get_UINT16BE(iter->xdr[iter->level].fdr.saa) != 0)
1383            printf("ninou");
1384
1385         read_sector_logical_len(iter->image->file_handle,
1386                           get_UINT16BE(iter->xdr[iter->level].fdr.paa) * get_UINT16BE(iter->image->sec0.spa),
1387                           & iter->image->geometry, &dor, sizeof(dor));
1388
1389         iter->level++;
1390         iter->nrc[iter->level] = get_UINT16BE(dor.nrc)/*get_UINT32BE(iter->fdr[iter->level-1].eom)-1*/;
1391         iter->index[iter->level] = 0;
1392         /*if (get_UINT16BE(dor.nrc) != (get_UINT32BE(iter->xdr[iter->level-1].fdr.eom)-1))
1393            printf("hiha");*/
1394      }
1395
1396      /* go to upper level if applicable */
1397      while (iter->index[iter->level] >= iter->nrc[iter->level])
1398         iter->level--;
1399   }
1400
1401   return 0;
1402}
1403
1404/*
1405   Free enumerator
1406*/
1407static void ti990_image_closeenum(imgtool_directory *enumeration)
1408{
1409}
1410
1411/*
1412   Compute free space on disk image (in ADUs)
1413*/
1414static imgtoolerr_t ti990_image_freespace(imgtool_partition *partition, UINT64 *size)
1415{
1416   imgtool_image *img = imgtool_partition_image(partition);
1417   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1418   int totadus = get_UINT16BE(image->sec0.tna);
1419   int adu, record, sub_adu;
1420   char buf[256];
1421   size_t freeadus = 0;
1422
1423   if ((totadus+2031)/2032 != image->sec0.tbm)
1424      /*return IMGTOOLERR_CORRUPTIMAGE;*/
1425      return 0;
1426
1427   adu = 0;
1428   record = 0;
1429   sub_adu = 0;
1430   while (adu<totadus)
1431   {
1432      read_sector_logical_len(image->file_handle, image->sec0.sbm + record, &image->geometry, buf, sizeof(buf));
1433
1434      while ((adu < totadus) && (sub_adu < 2032))
1435      {
1436         if (! (buf[(sub_adu >> 3) + 2] & (1 << (sub_adu & 7))))
1437            freeadus++;
1438         sub_adu++;
1439         adu++;
1440      }
1441      sub_adu = 0;
1442      record++;
1443   }
1444
1445   * size = freeadus;
1446
1447   return IMGTOOLERR_SUCCESS;
1448}
1449
1450#ifdef UNUSED_FUNCTION
1451/*
1452   Extract a file from a ti990_image.
1453*/
1454static imgtoolerr_t ti990_image_readfile(imgtool_partition *partition, const char *fpath, imgtool_stream *destf)
1455{
1456   imgtool_image *img = imgtool_partition_image(partition);
1457   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1458   int catalog_index, fdr_secnum, parent_fdr_secnum;
1459   imgtoolerr_t reply;
1460
1461
1462   reply = find_fdr(image, fpath, &catalog_index, &fdr_secnum, &parent_fdr_secnum);
1463   if (reply)
1464      return reply;
1465
1466   /* ... */
1467
1468   return 0;
1469
1470#if 0
1471   ti99_image *image = (ti99_image*) img;
1472   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
1473   char ti_fname[10];
1474   ti99_fdr fdr;
1475   tifile_header dst_header;
1476   int i, lnks_index;
1477   int cur_sec, last_sec;
1478   int secsused;
1479   UINT8 buf[256];
1480   int reply;
1481
1482   str_to_fname(ti_fname, filename);
1483
1484   reply = find_fdr(image, ti_fname, &fdr, NULL);
1485   if (reply)
1486      return reply;
1487
1488   dst_header.tifiles[0] = '\7';
1489   dst_header.tifiles[1] = 'T';
1490   dst_header.tifiles[2] = 'I';
1491   dst_header.tifiles[3] = 'F';
1492   dst_header.tifiles[4] = 'I';
1493   dst_header.tifiles[5] = 'L';
1494   dst_header.tifiles[6] = 'E';
1495   dst_header.tifiles[7] = 'S';
1496   dst_header.secsused_MSB = fdr.secsused_MSB;
1497   dst_header.secsused_LSB = fdr.secsused_LSB;
1498   dst_header.flags = fdr.flags;
1499   dst_header.recspersec = fdr.recspersec;
1500   dst_header.eof = fdr.eof;
1501   dst_header.reclen = fdr.reclen;
1502   dst_header.fixrecs_MSB = fdr.fixrecs_MSB;
1503   dst_header.fixrecs_LSB = fdr.fixrecs_LSB;
1504   for (i=0; i<(128-14); i++)
1505      dst_header.res[i] = 0;
1506
1507   if (stream_write(destf, & dst_header, 128) != 128)
1508      return IMGTOOLERR_WRITEERROR;
1509
1510
1511   secsused = get_fdr_secsused(&fdr);
1512
1513   i = 0;         /* file logical sector #0 */
1514   lnks_index = 0;   /* start of file block table */
1515   while (i<secsused)
1516   {
1517      if (lnks_index == 76)
1518         return IMGTOOLERR_CORRUPTIMAGE;
1519
1520      /* read curent file block table entry */
1521      cur_sec = ((fdr.lnks[lnks_index][1] & 0xf) << 8) | fdr.lnks[lnks_index][0];
1522      last_sec = (fdr.lnks[lnks_index][2] << 4) | (fdr.lnks[lnks_index][1] >> 4);
1523
1524      /* copy current file block */
1525      while ((i<=last_sec) && (i<secsused))
1526      {
1527         if (cur_sec >= totsecs)
1528            return IMGTOOLERR_CORRUPTIMAGE;
1529
1530         if (read_sector_logical(image->file_handle, cur_sec, & image->geometry, buf))
1531            return IMGTOOLERR_READERROR;
1532
1533         if (stream_write(destf, buf, 256) != 256)
1534            return IMGTOOLERR_WRITEERROR;
1535
1536         i++;
1537         cur_sec++;
1538      }
1539
1540      /* next entry in file block table */
1541      lnks_index++;
1542   }
1543#endif
1544
1545   return 0;
1546}
1547
1548/*
1549   Add a file to a ti990_image.
1550*/
1551static imgtoolerr_t ti990_image_writefile(imgtool_partition *partition, const char *fpath, imgtool_stream *sourcef, option_resolution *writeoptions)
1552{
1553   imgtool_image *img = imgtool_partition_image(partition);
1554   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1555   int catalog_index, fdr_secnum, parent_fdr_secnum;
1556   imgtoolerr_t reply;
1557
1558
1559   /* check that file does not exist */
1560   reply = find_fdr(image, fpath, &catalog_index, &fdr_secnum, &parent_fdr_secnum);
1561   if ((reply) && (reply != IMGTOOLERR_FILENOTFOUND))
1562      return reply;
1563
1564   /* ... */
1565
1566   return 0;
1567
1568#if 0
1569   ti99_image *image = (ti99_image*) img;
1570   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
1571   char ti_fname[10];
1572   ti99_fdr fdr;
1573   tifile_header src_header;
1574   int i, lnks_index;
1575   int cur_sec, last_sec;
1576   int secsused;
1577   UINT8 buf[256];
1578   int reply;
1579   int fdr_secnum;
1580
1581   str_to_fname(ti_fname, filename);
1582
1583   reply = find_fdr(image, ti_fname, &fdr, NULL);
1584   if (reply == 0)
1585   {   /* file already exists: causes an error for now */
1586      return IMGTOOLERR_UNEXPECTED;
1587   }
1588   else if (reply != IMGTOOLERR_FILENOTFOUND)
1589   {
1590      return reply;
1591   }
1592
1593   if (stream_read(sourcef, & src_header, 128) != 128)
1594      return IMGTOOLERR_READERROR;
1595
1596   /* create new file */
1597   reply = new_file(image, ti_fname, &fdr_secnum);
1598   if (reply)
1599      return reply;
1600
1601   memcpy(fdr.name, ti_fname, 10);
1602   fdr.res10[1] = fdr.res10[0] = 0;
1603   fdr.flags = src_header.flags;
1604   fdr.recspersec = src_header.recspersec;
1605   fdr.secsused_MSB = /*src_header.secsused_MSB*/0;
1606   fdr.secsused_LSB = /*src_header.secsused_LSB*/0;
1607   fdr.eof = src_header.eof;
1608   fdr.reclen = src_header.reclen;
1609   fdr.fixrecs_LSB = src_header.fixrecs_LSB;
1610   fdr.fixrecs_MSB = src_header.fixrecs_MSB;
1611   for (i=0; i<8; i++)
1612      fdr.res20[i] = 0;
1613   for (i=0; i<76; i++)
1614      fdr.lnks[i][2] = fdr.lnks[i][1] = fdr.lnks[i][0] = 0;
1615
1616   /* alloc data sectors */
1617   secsused = (src_header.secsused_MSB << 8) | src_header.secsused_LSB;
1618   reply = alloc_file_sectors(image, &fdr, secsused);
1619   if (reply)
1620      return reply;
1621
1622   /* copy data */
1623   i = 0;
1624   lnks_index = 0;
1625   while (i<secsused)
1626   {
1627      if (lnks_index == 76)
1628         return IMGTOOLERR_CORRUPTIMAGE;
1629
1630      cur_sec = ((fdr.lnks[lnks_index][1] & 0xf) << 8) | fdr.lnks[lnks_index][0];
1631      last_sec = (fdr.lnks[lnks_index][2] << 4) | (fdr.lnks[lnks_index][1] >> 4);
1632
1633      while ((i<secsused) && (i<=last_sec))
1634      {
1635         if (cur_sec >= totsecs)
1636            return IMGTOOLERR_CORRUPTIMAGE;
1637
1638         if (stream_read(sourcef, buf, 256) != 256)
1639            return IMGTOOLERR_READERROR;
1640
1641         if (write_sector_logical(image->file_handle, cur_sec, & image->geometry, buf))
1642            return IMGTOOLERR_WRITEERROR;
1643
1644         i++;
1645         cur_sec++;
1646      }
1647
1648      lnks_index++;
1649   }
1650
1651   /* write fdr */
1652   if (write_sector_logical(image->file_handle, fdr_secnum, & image->geometry, &fdr))
1653      return IMGTOOLERR_WRITEERROR;
1654
1655   /* update catalog */
1656   for (i=0; i<128; i++)
1657   {
1658      buf[2*i] = image->catalog[i].fdr_secnum >> 8;
1659      buf[2*i+1] = image->catalog[i].fdr_secnum & 0xff;
1660   }
1661   if (write_sector_logical(image->file_handle, 1, & image->geometry, buf))
1662      return IMGTOOLERR_WRITEERROR;
1663
1664   /* update bitmap */
1665   if (write_sector_logical(image->file_handle, 0, & image->geometry, &image->sec0))
1666      return IMGTOOLERR_WRITEERROR;
1667#endif
1668
1669   return 0;
1670}
1671
1672/*
1673   Delete a file from a ti990_image.
1674*/
1675static imgtoolerr_t ti990_image_deletefile(imgtool_partition *partition, const char *fpath)
1676{
1677   imgtool_image *img = imgtool_partition_image(partition);
1678   ti990_image *image = (ti990_image *) imgtool_image_extra_bytes(img);
1679   int catalog_index, fdr_secnum, parent_fdr_secnum;
1680   imgtoolerr_t reply;
1681
1682
1683   reply = find_fdr(image, fpath, &catalog_index, &fdr_secnum, &parent_fdr_secnum);
1684   if (reply)
1685      return reply;
1686
1687   /* ... */
1688
1689   return 0;
1690
1691#if 0
1692   ti99_image *image = (ti99_image*) img;
1693   int totsecs = (image->sec0.totsecsMSB << 8) | image->sec0.totsecsLSB;
1694   char ti_fname[10];
1695   ti99_fdr fdr;
1696   int i, lnks_index;
1697   int cur_sec, last_sec;
1698   int secsused;
1699   int catalog_index;
1700   int reply;
1701   UINT8 buf[256];
1702
1703   str_to_fname(ti_fname, filename);
1704
1705   reply = find_fdr(image, ti_fname, &fdr, &catalog_index);
1706   if (reply)
1707      return reply;
1708
1709   /* free data sectors */
1710   secsused = get_fdr_secsused(&fdr);
1711
1712   i = 0;
1713   lnks_index = 0;
1714   while (i<secsused)
1715   {
1716      if (lnks_index == 76)
1717         return IMGTOOLERR_CORRUPTIMAGE;
1718
1719      cur_sec = ((fdr.lnks[lnks_index][1] & 0xf) << 8) | fdr.lnks[lnks_index][0];
1720      last_sec = (fdr.lnks[lnks_index][2] << 4) | (fdr.lnks[lnks_index][1] >> 4);
1721
1722      while ((i<secsused) && (i<=last_sec))
1723      {
1724         if (cur_sec >= totsecs)
1725            return IMGTOOLERR_CORRUPTIMAGE;
1726
1727         image->sec0.abm[cur_sec >> 3] &= ~ (1 << (cur_sec & 7));
1728
1729         i++;
1730         cur_sec++;
1731      }
1732
1733      lnks_index++;
1734   }
1735
1736   /* free fdr sector */
1737   image->sec0.abm[image->catalog[catalog_index].fdr_secnum >> 3] &= ~ (1 << (image->catalog[catalog_index].fdr_secnum & 7));
1738
1739   /* delete catalog entry */
1740   for (i=catalog_index; i<127; i++)
1741      image->catalog[i] = image->catalog[i+1];
1742   image->catalog[127].fdr_secnum = 0;
1743
1744   /* update catalog */
1745   for (i=0; i<128; i++)
1746   {
1747      buf[2*i] = image->catalog[i].fdr_secnum >> 8;
1748      buf[2*i+1] = image->catalog[i].fdr_secnum & 0xff;
1749   }
1750   if (write_sector_logical(image->file_handle, 1, & image->geometry, buf))
1751      return IMGTOOLERR_WRITEERROR;
1752
1753   /* update bitmap */
1754   if (write_sector_logical(image->file_handle, 0, & image->geometry, &image->sec0))
1755      return IMGTOOLERR_WRITEERROR;
1756#endif
1757
1758   return 0;
1759}
1760#endif
1761
1762/*
1763   Create a blank ti990_image.
1764*/
1765static imgtoolerr_t ti990_image_create(imgtool_image *image, imgtool_stream *f, option_resolution *createoptions)
1766{
1767   //const char *volname;
1768   ti990_geometry geometry;
1769   unsigned totsecs;
1770   disk_image_header header;
1771   ti990_sc0 sec0;
1772   UINT8 empty_sec[MAX_SECTOR_SIZE];
1773   int reply;
1774   int i;
1775
1776   /* read options */
1777   //volname = option_resolution_lookup_string(createoptions, ti990_createopts_volname);
1778   geometry.cylinders = option_resolution_lookup_int(createoptions, ti990_createopts_cylinders);
1779   geometry.heads = option_resolution_lookup_int(createoptions, ti990_createopts_heads);
1780   geometry.sectors_per_track = option_resolution_lookup_int(createoptions, ti990_createopts_sectors);
1781   geometry.bytes_per_sector = option_resolution_lookup_int(createoptions, ti990_createopts_sectorsize);
1782
1783   totsecs = geometry.cylinders * geometry.heads * geometry.sectors_per_track;
1784
1785   /* write header */
1786   set_UINT32BE(& header.cylinders, geometry.cylinders);
1787   set_UINT32BE(& header.heads, geometry.heads);
1788   set_UINT32BE(& header.sectors_per_track, geometry.sectors_per_track);
1789   set_UINT32BE(& header.bytes_per_sector, geometry.bytes_per_sector);
1790
1791   reply = stream_write(f, &header, sizeof(header));
1792   if (reply != sizeof(header))
1793   {
1794      return IMGTOOLERR_WRITEERROR;
1795   }
1796
1797
1798   /* initialize sector 0 */
1799   /* mark disk as uninitialized */
1800   set_UINT16BE(& sec0.sta, 2);
1801
1802
1803   /* write sector 0 */
1804   if (write_sector_logical(f, 0, & geometry, &sec0))
1805      return IMGTOOLERR_WRITEERROR;
1806
1807
1808   /* now clear every other sector, including catalog */
1809   memset(empty_sec, 0, geometry.bytes_per_sector);
1810
1811   for (i=1; i<totsecs; i++)
1812      if (write_sector_logical(f, i, & geometry, empty_sec))
1813         return IMGTOOLERR_WRITEERROR;
1814
1815   return 0;
1816}
src/mess/tools/imgtool/modules/concept.c
r0r1340
1/*
2   Handlers for concept floppy images
3
4   Disk images are in MESS format.
5
6   Raphael Nabet, 2003
7*/
8
9#include <stdio.h>
10#include <string.h>
11#include <stdlib.h>
12#include <limits.h>
13#include <assert.h>
14#include "osdepend.h"
15#include "imgtoolx.h"
16
17typedef struct UINT16xE
18{
19   UINT8 bytes[2];
20} UINT16xE;
21
22/*
23   get_UINT16xE
24
25   Read a 16-bit word, whether it is little-endian or big-endian
26
27   little_endian (I): non-zero if word is little-endian, zero if word is
28      big-endian
29   word (I): pointer to word to read
30
31   Returns value of word in native format
32*/
33INLINE UINT16 get_UINT16xE(int little_endian, UINT16xE word)
34{
35   return little_endian ? (word.bytes[0] | (word.bytes[1] << 8)) : ((word.bytes[0] << 8) | word.bytes[1]);
36}
37
38/*
39   set_UINT16xE
40
41   Write a 16-bit word, whether it is little-endian or big-endian
42
43   little_endian (I): non-zero if word is little-endian, zero if word is
44      big-endian
45   word (O): pointer to word to write
46   data (I): value to write in word, in native format
47*/
48INLINE void set_UINT16xE(int little_endian, UINT16xE *word, UINT16 data)
49{
50   if (little_endian)
51   {
52      word->bytes[0] = data & 0xff;
53      word->bytes[1] = (data >> 8) & 0xff;
54   }
55   else
56   {
57      word->bytes[0] = (data >> 8) & 0xff;
58      word->bytes[1] = data & 0xff;
59   }
60}
61
62/*
63   Disk structure:
64
65   Track 0 Sector 0 & 1: bootstrap loader
66   Track 0 Sector 2 through 5: disk directory
67   Remaining sectors are used for data.
68*/
69
70/*
71   device directory record (Disk sector 2-5)
72*/
73
74typedef struct concept_vol_hdr_entry
75{
76   UINT16xE   first_block;
77   UINT16xE   next_block;
78   UINT16xE   ftype;
79
80   unsigned char   volname[8];
81   UINT16xE   last_block;
82   UINT16xE   num_files;
83   UINT16xE   last_boot;
84   UINT16xE   last_access;
85   char      mem_flipped;
86   char      disk_flipped;
87   UINT16xE   unused;
88} concept_vol_hdr_entry;
89
90typedef struct concept_file_dir_entry
91{
92   UINT16xE   first_block;
93   UINT16xE   next_block;
94   UINT16xE   ftype;
95
96   unsigned char   filename[16];
97   UINT16xE   last_byte;
98   UINT16xE   last_access;
99} concept_file_dir_entry;
100
101typedef struct concept_dev_dir
102{
103   concept_vol_hdr_entry vol_hdr;
104   concept_file_dir_entry file_dir[77];
105   char unused[20];
106} concept_dev_dir;
107
108/*
109   concept disk image descriptor
110*/
111typedef struct concept_image
112{
113   imgtool_stream *file_handle;      /* imgtool file handle */
114   concept_dev_dir dev_dir;   /* cached copy of device directory */
115} concept_image;
116
117/*
118   concept catalog iterator, used when imgtool reads the catalog
119*/
120typedef struct concept_iterator
121{
122   concept_image *image;
123   int index;                     /* current index */
124} concept_iterator;
125
126
127static imgtoolerr_t concept_image_init(imgtool_image *img, imgtool_stream *f);
128static void concept_image_exit(imgtool_image *img);
129static void concept_image_info(imgtool_image *img, char *string, size_t len);
130static imgtoolerr_t concept_image_beginenum(imgtool_directory *enumeration, const char *path);
131static imgtoolerr_t concept_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
132static void concept_image_closeenum(imgtool_directory *enumeration);
133static imgtoolerr_t concept_image_freespace(imgtool_partition *partition, UINT64 *size);
134static imgtoolerr_t concept_image_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf);
135/*static imgtoolerr_t concept_image_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions);
136static imgtoolerr_t concept_image_deletefile(imgtool_partition *partition, const char *filename);
137static imgtoolerr_t concept_image_create(const imgtool_module *mod, imgtool_stream *f, option_resolution *createoptions);*/
138
139void concept_get_info(const imgtool_class *imgclass, UINT32 state, union imgtoolinfo *info)
140{
141   switch(state)
142   {
143      /* --- the following bits of info are returned as 64-bit signed integers --- */
144      case IMGTOOLINFO_INT_IMAGE_EXTRA_BYTES:            info->i = sizeof(concept_image); break;
145      case IMGTOOLINFO_INT_DIRECTORY_EXTRA_BYTES:            info->i = sizeof(concept_iterator); break;
146
147      /* --- the following bits of info are returned as NULL-terminated strings --- */
148      case IMGTOOLINFO_STR_NAME:                     strcpy(info->s = imgtool_temp_str(), "concept"); break;
149      case IMGTOOLINFO_STR_DESCRIPTION:               strcpy(info->s = imgtool_temp_str(), "Concept floppy disk image"); break;
150      case IMGTOOLINFO_STR_FILE_EXTENSIONS:            strcpy(info->s = imgtool_temp_str(), "img"); break;
151      case IMGTOOLINFO_STR_EOLN:                     strcpy(info->s = imgtool_temp_str(), "\r"); break;
152
153      /* --- the following bits of info are returned as pointers to data or functions --- */
154      case IMGTOOLINFO_PTR_OPEN:                     info->open = concept_image_init; break;
155      case IMGTOOLINFO_PTR_CLOSE:                     info->close = concept_image_exit; break;
156      case IMGTOOLINFO_PTR_INFO:                     info->info = concept_image_info; break;
157      case IMGTOOLINFO_PTR_BEGIN_ENUM:               info->begin_enum = concept_image_beginenum; break;
158      case IMGTOOLINFO_PTR_NEXT_ENUM:                  info->next_enum = concept_image_nextenum; break;
159      case IMGTOOLINFO_PTR_CLOSE_ENUM:               info->close_enum = concept_image_closeenum; break;
160      case IMGTOOLINFO_PTR_FREE_SPACE:               info->free_space = concept_image_freespace; break;
161      case IMGTOOLINFO_PTR_READ_FILE:                  info->read_file = concept_image_readfile; break;
162      case IMGTOOLINFO_PTR_WRITE_FILE:               /* info->write_file = concept_image_writefile */; break;
163      case IMGTOOLINFO_PTR_DELETE_FILE:               /* info->delete_file = concept_image_deletefile */; break;
164      case IMGTOOLINFO_PTR_CREATE:                  /* info->create = concept_image_create */; break;
165   }
166}
167
168/*
169   read_physical_record
170
171   Read one 512-byte physical record from a disk image
172
173   file_handle: imgtool file handle
174   secnum: physical record address
175   dest: pointer to destination buffer
176
177   Return non-zero on error
178*/
179static int read_physical_record(imgtool_stream *file_handle, int secnum, void *dest)
180{
181   int reply;
182
183   /* seek to sector */
184   reply = stream_seek(file_handle, secnum*512, SEEK_SET);
185   if (reply)
186      return 1;
187   /* read it */
188   reply = stream_read(file_handle, dest, 512);
189   if (reply != 512)
190      return 1;
191
192   return 0;
193}
194
195#ifdef UNUSED_FUNCTION
196/*
197   write_physical_record
198
199   Write one 512-byte physical record to a disk image
200
201   file_handle: imgtool file handle
202   secnum: logical sector address
203   src: pointer to source buffer
204
205   Return non-zero on error
206*/
207static int write_physical_record(imgtool_stream *file_handle, int secnum, const void *src)
208{
209   int reply;
210
211   /* seek to sector */
212   reply = stream_seek(file_handle, secnum*512, SEEK_SET);
213   if (reply)
214      return 1;
215   /* read it */
216   reply = stream_write(file_handle, src, 512);
217   if (reply != 512)
218      return 1;
219
220   return 0;
221}
222#endif
223
224/*
225   Search for a file name on a concept_image
226
227   image (I): image reference
228   filename (I): name of the file to search
229   entry_index (O): index of file in disk catalog
230
231   Return non-zero on error
232*/
233static int get_catalog_entry(concept_image *image, const unsigned char *filename, int *entry_index)
234{
235   int filename_len = filename[0];
236   int i;
237
238   if (filename_len > 15)
239      /* file name is bad */
240      return 1;
241
242   for (i = 0; i < 77; i++)
243   {
244      if (!memcmp(filename, image->dev_dir.file_dir[i].filename, filename_len+1))
245      {
246         /* file found */
247         *entry_index = i;
248         return 0;
249      }
250   }
251
252   /* file not found */
253   return 1;
254}
255
256/*
257   Open a file as a concept_image.
258*/
259static imgtoolerr_t concept_image_init(imgtool_image *img, imgtool_stream *f)
260{
261   concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);
262   int reply;
263   int i;
264   unsigned totphysrecs;
265
266   image->file_handle = f;
267
268   /* read device directory */
269   for (i=0; i<4; i++)
270   {
271      reply = read_physical_record(f, i+2, ((char *) & image->dev_dir)+i*512);
272      if (reply)
273         return IMGTOOLERR_READERROR;
274   }
275
276   /* do primitive checks */
277   totphysrecs = get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.last_block)
278               - get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.first_block);
279
280   if ((get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.first_block) != 0)
281      || (get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.next_block) != 6)
282      || (totphysrecs < 6) /*|| (stream_size(f) != totphysrecs*512)*/
283      || (image->dev_dir.vol_hdr.volname[0] > 7))
284   {
285      return IMGTOOLERR_CORRUPTIMAGE;
286   }
287
288   return IMGTOOLERR_SUCCESS;
289}
290
291/*
292   close a concept_image
293*/
294static void concept_image_exit(imgtool_image *img)
295{
296   /*concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);*/
297}
298
299/*
300   get basic information on a concept_image
301
302   Currently returns the volume name
303*/
304static void concept_image_info(imgtool_image *img, char *string, size_t len)
305{
306   concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);
307   char vol_name[8];
308
309   memcpy(vol_name, image->dev_dir.vol_hdr.volname + 1, image->dev_dir.vol_hdr.volname[0]);
310   vol_name[image->dev_dir.vol_hdr.volname[0]] = 0;
311
312   snprintf(string, len, "%s", vol_name);
313}
314
315/*
316   Open the disk catalog for enumeration
317*/
318static imgtoolerr_t concept_image_beginenum(imgtool_directory *enumeration, const char *path)
319{
320   concept_iterator *iter;
321
322   iter = (concept_iterator *) imgtool_directory_extrabytes(enumeration);
323   iter->image = (concept_image *) imgtool_image_extra_bytes(imgtool_directory_image(enumeration));
324   iter->index = 0;
325   return IMGTOOLERR_SUCCESS;
326}
327
328/*
329   Enumerate disk catalog next entry
330*/
331static imgtoolerr_t concept_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
332{
333   concept_iterator *iter = (concept_iterator *) imgtool_directory_extrabytes(enumeration);
334
335
336   ent->corrupt = 0;
337   ent->eof = 0;
338
339   if ((iter->image->dev_dir.file_dir[iter->index].filename[0] == 0) || (iter->index > 77))
340   {
341      ent->eof = 1;
342   }
343   else if (iter->image->dev_dir.file_dir[iter->index].filename[0] > 15)
344   {
345      ent->corrupt = 1;
346   }
347   else
348   {
349      int len = iter->image->dev_dir.file_dir[iter->index].filename[0];
350      const char *type;
351
352      if (len > sizeof(ent->filename) / sizeof(ent->filename[0]))
353         len = sizeof(ent->filename) / sizeof(ent->filename[0]);
354      memcpy(ent->filename, iter->image->dev_dir.file_dir[iter->index].filename + 1, len);
355      ent->filename[len] = 0;
356
357      /* parse flags */
358      switch (get_UINT16xE(iter->image->dev_dir.vol_hdr.disk_flipped, iter->image->dev_dir.file_dir[iter->index].ftype) & 0xf)
359      {
360      case 0:
361      case 8:
362         type = "DIRHDR";
363         break;
364      case 2:
365         type = "CODE";
366         break;
367      case 3:
368         type = "TEXT";
369         break;
370      case 5:
371         type = "DATA";
372         break;
373      default:
374         type = "???";
375         break;
376      }
377      snprintf(ent->attr, sizeof(ent->attr) / sizeof(ent->attr[0]), "%s", type);
378
379      /* len in physrecs */
380      ent->filesize = get_UINT16xE(iter->image->dev_dir.vol_hdr.disk_flipped, iter->image->dev_dir.file_dir[iter->index].next_block)
381                     - get_UINT16xE(iter->image->dev_dir.vol_hdr.disk_flipped, iter->image->dev_dir.file_dir[iter->index].first_block);
382
383      iter->index++;
384   }
385
386   return 0;
387}
388
389/*
390   Free enumerator
391*/
392static void concept_image_closeenum(imgtool_directory *enumeration)
393{
394}
395
396/*
397   Compute free space on disk image
398*/
399static imgtoolerr_t concept_image_freespace(imgtool_partition *partition, UINT64 *size)
400{
401   imgtool_image *img = imgtool_partition_image(partition);
402   concept_image *image = (concept_image*) img;
403   int free_blocks;
404   int i;
405
406   /* first get number of data blocks */
407   free_blocks = get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.last_block)
408               - get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.vol_hdr.next_block);
409
410   /* next substract lenght of each file */
411   for (i=0; (image->dev_dir.file_dir[i].filename[0] != 0) && (i <= 77); i++)
412   {
413      free_blocks -= get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[i].next_block)
414                  - get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[i].first_block);
415   }
416
417   *size = free_blocks;
418
419   return IMGTOOLERR_SUCCESS;
420}
421
422/*
423   Extract a file from a concept_image.
424*/
425static imgtoolerr_t concept_image_readfile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *destf)
426{
427   imgtool_image *img = imgtool_partition_image(partition);
428   concept_image *image = (concept_image *) imgtool_image_extra_bytes(img);
429   size_t filename_len = strlen(filename);
430   unsigned char concept_fname[16];
431   int catalog_index;
432   int i;
433   UINT8 buf[512];
434
435   if (filename_len > 15)
436      return IMGTOOLERR_BADFILENAME;
437
438   concept_fname[0] = filename_len;
439   memcpy(concept_fname+1, filename, filename_len);
440
441   if (get_catalog_entry(image, concept_fname, &catalog_index))
442      return IMGTOOLERR_FILENOTFOUND;
443
444   for (i = get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[catalog_index].first_block);
445         i < get_UINT16xE(image->dev_dir.vol_hdr.disk_flipped, image->dev_dir.file_dir[catalog_index].next_block);
446         i++)
447   {
448      if (read_physical_record(image->file_handle, i, buf))
449         return IMGTOOLERR_READERROR;
450
451      if (stream_write(destf, buf, 512) != 512)
452         return IMGTOOLERR_WRITEERROR;
453   }
454
455   return 0;
456}
457
458#if 0
459/*
460   Add a file to a concept_image.
461*/
462static imgtoolerr_t concept_image_writefile(imgtool_partition *partition, const char *filename, const char *fork, imgtool_stream *sourcef, option_resolution *writeoptions)
463{
464   /* ... */
465
466   return 0;
467}
468
469/*
470   Delete a file from a concept_image.
471*/
472static imgtoolerr_t concept_image_deletefile(imgtool_partition *partition, const char *filename)
473{
474   /* ... */
475
476   return 0;
477}
478
479/*
480   Create a blank concept_image.
481*/
482static imgtoolerr_t concept_image_create(const imgtool_module *mod, imgtool_stream *f, option_resolution *createoptions)
483{
484   /* ... */
485
486   return 0;
487}
488#endif
src/mess/tools/imgtool/modules/xsa.c
r0r1340
1/*
2 * xsa.c : decompresses XelaSoft Archives.
3 *
4 * Sean Young
5 */
6
7#include "osdepend.h"
8#include "imgtoolx.h"
9#include "utils.h"
10
11
12typedef struct {
13   imgtool_image         base;
14   char         *file_name;
15   imgtool_stream          *file_handle;
16   int          size;
17   } XSA_IMAGE;
18
19typedef struct
20   {
21   imgtool_directory    base;
22   XSA_IMAGE   *image;
23   int         index;
24   } XSA_ITERATOR;
25
26static int xsa_extract (imgtool_stream *in, imgtool_stream *out);
27static int xsa_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
28static void xsa_image_exit(imgtool_image *img);
29static int xsa_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
30static int xsa_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
31static void xsa_image_closeenum(imgtool_directory *enumeration);
32static int xsa_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
33
34IMAGEMODULE(
35   xsa,
36   "XelaSoft Archive",            /* human readable name */
37   "xsa",                     /* file extension */
38   NULL,                     /* crcfile */
39   NULL,                     /* crc system name */
40   NULL,                     /* eoln */
41   0,                        /* flags */
42   xsa_image_init,               /* init function */
43   xsa_image_exit,               /* exit function */
44   NULL,                     /* info function */
45   xsa_image_beginenum,         /* begin enumeration */
46   xsa_image_nextenum,            /* enumerate next */
47   xsa_image_closeenum,         /* close enumeration */
48   NULL,                     /* free space on image */
49   xsa_image_readfile,            /* read file */
50   NULL,                     /* write file */
51   NULL,                     /* delete file */
52   NULL,                     /* create image */
53   NULL,                     /* read sector */
54   NULL,                     /* write sector */
55   NULL,                     /* file options */
56   NULL                     /* create options */
57)
58
59static int xsa_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
60   {
61   XSA_IMAGE *image;
62   int pos, len, size;
63    UINT8 header[4], byt;
64   char *file_name, *file_name_new;
65
66   size = stream_size (f);
67   if (size < 5) return IMGTOOLERR_MODULENOTFOUND;
68   if (4 != stream_read (f, header, 4) ) return IMGTOOLERR_READERROR;
69   
70    if (memcmp (header, "PCK\010", 4) )
71      return IMGTOOLERR_MODULENOTFOUND;
72   
73   if (4 != stream_read (f, &size, 4) ) return IMGTOOLERR_READERROR;
74   size = LITTLE_ENDIANIZE_INT32 (size);
75   if (4 != stream_read (f, header, 4) ) return IMGTOOLERR_READERROR;
76   
77   /* get name from XSA header, can't be longer than 8.3 really */
78   /* but could be, it's zero-terminated */
79   file_name = NULL;
80   pos = len = 0;
81   while (1)
82      {
83      if (1 != stream_read (f, &byt, 1) )
84         {
85         if (file_name) free (file_name);
86         *outimg=NULL;
87         return IMGTOOLERR_READERROR;
88         }
89      if (len <= pos)
90         {
91         len += 8; /* why 8? */
92         file_name_new = realloc (file_name, len);
93         if (!file_name_new)
94            {
95            if (file_name) free (file_name);
96            *outimg=NULL;
97            return IMGTOOLERR_OUTOFMEMORY;
98            }
99         file_name = file_name_new;
100         }
101      file_name[pos++] = byt;
102      if (!byt) break;
103      }
104
105   image = (XSA_IMAGE*)malloc (sizeof (XSA_IMAGE) );
106   if (!image) return IMGTOOLERR_OUTOFMEMORY;
107   *outimg = (imgtool_image*)image;
108
109   memset(image, 0, sizeof(XSA_IMAGE));
110   image->base.module = mod;
111   image->file_handle = f;
112   image->size = size;
113   image->file_name = file_name;
114
115   return 0;
116   }
117
118static void xsa_image_exit(imgtool_image *img)
119   {
120   XSA_IMAGE *image=(XSA_IMAGE*)img;
121   stream_close(image->file_handle);
122   free(image->file_name);
123   free(image);
124   }
125
126static int xsa_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
127   {
128   XSA_IMAGE *image=(XSA_IMAGE*)img;
129   XSA_ITERATOR *iter;
130
131   iter=*(XSA_ITERATOR**)outenum = (XSA_ITERATOR*) malloc(sizeof(XSA_ITERATOR));
132   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
133
134   iter->base.module = img->module;
135
136   iter->image=image;
137   iter->index = 0;
138   return 0;
139   }
140
141static int xsa_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
142   {
143   XSA_ITERATOR *iter=(XSA_ITERATOR*)enumeration;
144
145   ent->eof = iter->index;
146   if (!ent->eof)
147      {
148      strcpy (ent->fname, iter->image->file_name);
149
150      ent->corrupt=0;
151      ent->filesize = iter->image->size;
152
153      iter->index++;
154      }
155
156   return 0;
157   }
158
159static void xsa_image_closeenum(imgtool_directory *enumeration)
160   {
161   free(enumeration);
162   }
163
164static int xsa_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
165   {
166   XSA_IMAGE *image=(XSA_IMAGE*)img;
167
168   /*  check file name */
169   if (mame_stricmp (fname, image->file_name) )
170      return IMGTOOLERR_MODULENOTFOUND;
171
172   return xsa_extract (image->file_handle, destf);
173   }
174
175
176/*
177 * .xsa decompression. Code stolen from :
178 *
179 * http://web.inter.nl.net/users/A.P.Wulms/
180 */
181
182
183/****************************************************************/
184/* LZ77 data decompression                              */
185/* Copyright (c) 1994 by XelaSoft                        */
186/* version history:                                    */
187/*   version 0.9, start date: 11-27-1994                  */
188/****************************************************************/
189
190#define SHORT unsigned
191
192#define slwinsnrbits (13)
193#define maxstrlen (254)
194
195#define maxhufcnt (127)
196#define logtblsize (4)
197
198
199#define tblsize (1<<logtblsize)
200
201typedef struct huf_node {
202  SHORT weight;
203  struct huf_node *child1, *child2;
204} huf_node;
205
206/****************************************************************/
207/* global vars                                       */
208/****************************************************************/
209static unsigned updhufcnt;
210static unsigned cpdist[tblsize+1];
211static unsigned cpdbmask[tblsize];
212static unsigned cpdext[] = { /* Extra bits for distance codes */
213          0,  0,  0,  0,  1,  2,  3,  4,
214          5,  6,  7,  8,  9, 10, 11, 12};
215
216static SHORT tblsizes[tblsize];
217static huf_node huftbl[2*tblsize-1];
218
219/****************************************************************/
220/* maak de huffman codeer informatie                     */
221/****************************************************************/
222static void mkhuftbl( void )
223{
224  unsigned count;
225  huf_node  *hufpos;
226  huf_node  *l1pos, *l2pos;
227  SHORT tempw;
228
229  /* Initialize the huffman tree */
230  for (count=0, hufpos=huftbl; count != tblsize; count++) {
231    (hufpos++)->weight=1+(tblsizes[count] >>= 1);
232  }
233  for (count=tblsize; count != 2*tblsize-1; count++)
234    (hufpos++)->weight=-1;
235
236  /* Place the nodes in the correct manner in the tree */
237  while (huftbl[2*tblsize-2].weight == -1) {
238    for (hufpos=huftbl; !(hufpos->weight); hufpos++)
239      ;
240    l1pos = hufpos++;
241    while (!(hufpos->weight))
242      hufpos++;
243    if (hufpos->weight < l1pos->weight) {
244      l2pos = l1pos;
245      l1pos = hufpos++;
246    }
247    else
248      l2pos = hufpos++;
249    while ((tempw=(hufpos)->weight) != -1) {
250      if (tempw) {
251        if (tempw < l1pos->weight) {
252          l2pos = l1pos;
253          l1pos = hufpos;
254        }
255        else if (tempw < l2pos->weight)
256          l2pos = hufpos;
257      }
258      hufpos++;
259    }
260    hufpos->weight = l1pos->weight+l2pos->weight;
261    (hufpos->child1 = l1pos)->weight = 0;
262    (hufpos->child2 = l2pos)->weight = 0;
263  }
264  updhufcnt = maxhufcnt;
265}
266
267/****************************************************************/
268/* initialize the huffman info tables                           */
269/****************************************************************/
270static void inithufinfo( void )
271{
272  unsigned offs, count;
273
274  for (offs=1, count=0; count != tblsize; count++) {
275    cpdist[count] = offs;
276    offs += (cpdbmask[count] = 1<<cpdext[count]);
277  }
278  cpdist[count] = offs;
279
280  for (count = 0; count != tblsize; count++) {
281    tblsizes[count] = 0; /* reset the table counters */
282    huftbl[count].child1 = 0;  /* mark the leave nodes */
283  }
284  mkhuftbl(); /* make the huffman table */
285}
286
287/****************************************************************/
288/* global vars                                       */
289/****************************************************************/
290static imgtool_stream *in_stream, *out_stream;
291
292static UINT8 *outbuf;       /* the output buffer     */
293static UINT8 *outbufpos;    /* pos in output buffer  */
294static int outbufcnt;  /* #elements in the output buffer */
295static int error_occ;
296
297static UINT8 bitflg;  /* flag with the bits */
298static UINT8 bitcnt;  /* #resterende bits   */
299
300#define slwinsize (1 << slwinsnrbits)
301#define outbufsize (slwinsize+4096)
302
303/****************************************************************/
304/* The function prototypes                              */
305/****************************************************************/
306static void unlz77( void );       /* perform the real decompression       */
307static void charout(UINT8);      /* put a character in the output stream */
308static unsigned rdstrlen( void ); /* read string length                   */
309static unsigned rdstrpos( void ); /* read string pos                      */
310static void flushoutbuf( void );
311static UINT8 charin( void );       /* read a char                          */
312static UINT8 bitin( void );        /* read a bit                           */
313
314/****************************************************************/
315/* de hoofdlus                                       */
316/****************************************************************/
317static int xsa_extract (imgtool_stream *in, imgtool_stream *out)
318    {
319    UINT8 byt;
320
321   /* setup the in-stream */
322   stream_seek (in, 12, SEEK_SET);
323    do  {
324      if (1 != stream_read (in, &byt, 1) )
325         return IMGTOOLERR_READERROR;
326      } while (byt);
327   in_stream = in;
328    bitcnt = 0;         /* nog geen bits gelezen               */
329
330   /* setup the out buffer */
331    outbuf = malloc (outbufsize);
332    if (!outbuf) return IMGTOOLERR_OUTOFMEMORY;
333    outbufcnt = 0;
334    outbufpos = outbuf; /* dadelijk vooraan in laden           */
335   out_stream = out;
336
337   /* let's do it .. */
338   inithufinfo(); /* initialize the cpdist tables */
339
340    error_occ = 0;
341    unlz77();         /* decrunch de data echt               */
342
343   free (outbuf);
344
345   return error_occ;
346    }
347
348/****************************************************************/
349/* the actual decompression algorithm itself               */
350/****************************************************************/
351static void unlz77( void )
352{
353  UINT8 strl = 0;
354  unsigned strpos;
355
356  do {
357    switch (bitin()) {
358      case 0 : charout(charin()); break;
359      case 1 : strl = rdstrlen();
360          if (strl == (maxstrlen+1))
361       break;
362          strpos = rdstrpos();
363          while (strl--)
364       charout(*(outbufpos-strpos));
365          strl = 0;
366          break;
367    }
368  }
369  while (strl != (maxstrlen+1)&&!error_occ);
370  flushoutbuf ();
371}
372
373/****************************************************************/
374/* Put the next character in the input buffer.                  */
375/* Take care that minimal 'slwinsize' chars are before the      */
376/* current position.                                            */
377/****************************************************************/
378static void charout(UINT8 ch)
379{
380  if (error_occ) return;
381
382  if ((outbufcnt++) == outbufsize) {
383    if ( (outbufsize-slwinsize) != stream_write (out_stream, outbuf, outbufsize-slwinsize) )
384       error_occ = IMGTOOLERR_WRITEERROR;
385
386    memcpy(outbuf, outbuf+outbufsize-slwinsize, slwinsize);
387    outbufpos = outbuf+slwinsize;
388    outbufcnt = slwinsize+1;
389  }
390  *(outbufpos++) = ch;
391}
392
393/****************************************************************/
394/* flush the output buffer                                      */
395/****************************************************************/
396static void flushoutbuf( void )
397{
398  if (!error_occ && outbufcnt) {
399    if (outbufcnt != stream_write (out_stream, outbuf, outbufcnt) )
400      error_occ = IMGTOOLERR_WRITEERROR;
401
402    outbufcnt = 0;
403  }
404}
405
406/****************************************************************/
407/* read string length                                 */
408/****************************************************************/
409static unsigned rdstrlen( void )
410{
411  UINT8 len;
412  UINT8 nrbits;
413
414  if (!bitin())
415    return 2;
416  if (!bitin())
417    return 3;
418  if (!bitin())
419    return 4;
420
421  for (nrbits = 2; (nrbits != 7) && bitin(); nrbits++)
422    ;
423
424  len = 1;
425  while (nrbits--)
426    len = (len << 1) | bitin();
427
428  return (unsigned)(len+1);
429}
430
431/****************************************************************/
432/* read string pos                                    */
433/****************************************************************/
434static unsigned rdstrpos( void )
435{
436  UINT8 nrbits;
437  UINT8 cpdindex;
438  unsigned strpos;
439  huf_node *hufpos;
440
441  hufpos = huftbl+2*tblsize-2;
442
443  while (hufpos->child1)
444    if (bitin()) {
445      hufpos = hufpos->child2;
446    }
447    else {
448      hufpos = hufpos->child1;
449    }
450  cpdindex = hufpos-huftbl;
451  tblsizes[cpdindex]++;
452
453  if (cpdbmask[cpdindex] >= 256) {
454    UINT8 strposmsb, strposlsb;
455
456    strposlsb = (unsigned)charin();  /* lees LSB van strpos */
457    strposmsb = 0;
458    for (nrbits = cpdext[cpdindex]-8; nrbits--; strposmsb |= bitin())
459      strposmsb <<= 1;
460    strpos = (unsigned)strposlsb | (((unsigned)strposmsb)<<8);
461  }
462  else {
463    strpos=0;
464    for (nrbits = cpdext[cpdindex]; nrbits--; strpos |= bitin())
465      strpos <<= 1;
466  }
467  if (!(updhufcnt--))
468    mkhuftbl(); /* make the huffman table */
469
470  return strpos+cpdist[cpdindex];
471}
472
473/****************************************************************/
474/* read a bit from the input file                        */
475/****************************************************************/
476static UINT8 bitin( void )
477{
478  UINT8 temp;
479
480  if (!bitcnt) {
481    bitflg = charin();  /* lees de bitflg in */
482    bitcnt = 8;         /* nog 8 bits te verwerken */
483  }
484  temp = bitflg & 1;
485  bitcnt--;  /* weer 1 bit verwerkt */
486  bitflg >>= 1;
487
488  return temp;
489}
490
491/****************************************************************/
492/* Get the next character from the input buffer.                */
493/****************************************************************/
494static UINT8 charin( void )
495   {
496   UINT8 byte;
497
498   if (error_occ)
499      return 0;
500   else
501        {
502      if (1 != stream_read (in_stream, &byte, 1) )
503         {
504         error_occ = IMGTOOLERR_READERROR;
505         return 0;
506         }
507      else
508         return byte;
509      }
510   }
src/mess/tools/imgtool/modules/d64.c
r0r1340
1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4#include <assert.h>
5#include "osdepend.h"
6#include "imgtoolx.h"
7#include "d64.h"
8
9#ifdef LSB_FIRST
10typedef UINT16 littleuword;
11#define GET_UWORD(a) a
12#define SET_UWORD(a,v) a=v
13#else
14typedef struct {
15   unsigned char low, high;
16} littleuword;
17#define GET_UWORD(a) (a.low|(a.high<<8))
18#define SET_UWORD(a,v) a.low=(v)&0xff;a.high=((v)>>8)&0xff
19#endif
20
21/* tracks 1 to 35
22 * sectors number from 0
23 * each sector holds 256 data bytes
24 * directory and Bitmap Allocation Memory in track 18
25 * sector 0:
26 * 0: track# of directory begin (this linkage of sector often used)
27 * 1: sector# of directory begin
28 *
29 * BAM entries (one per track)
30 * offset 0: # of free sectors
31 * offset 1: sector 0 (lsb) free to sector 7
32 * offset 2: sector 8 to 15
33 * offset 3: sector 16 to whatever the number to sectors in track is
34 *
35 * directory sector:
36 * 0,1: track sector of next directory sector
37 * 2, 34, 66, ... : 8 directory entries
38 *
39 * directory entry:
40 * 0: file type
41 * (0x = scratched/splat, 8x = alive, Cx = locked
42 * where x: 0=DEL, 1=SEQ, 2=PRG, 3=USR, 4=REL)
43 * 1,2: track and sector of file
44 * 3..18: file name padded with a0
45 * 19,20: REL files side sector
46 * 21: REL files record length
47 * 28,29: number of blocks in file
48 * ended with illegal track and sector numbers
49 */
50
51// x64 d64 image with 64 byte header
52
53#define D64_MAX_TRACKS 40
54
55static int d64_sectors_per_track[] =
56{
57   21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
58   19, 19, 19, 19, 19, 19, 19,
59   18, 18, 18, 18, 18, 18,
60   17, 17, 17, 17, 17,
61   17, 17, 17, 17, 17 // non standard
62};
63
64static int d64_offset[D64_MAX_TRACKS+1];         /* offset of begin of track in d64 file */
65
66typedef struct {
67   unsigned char track, sector, // of next directory
68      format, doublesided;
69   struct { unsigned char free, map[3]; } bam[35];
70   unsigned char name[0x10], filler[2], id[2], filler2, version[2], filler3[4];
71   unsigned char unused[50]; // zero
72   unsigned char free2[35]; //freecount for 1751 tracks 36..70
73} D64_HEADER;
74
75typedef struct {
76   unsigned char unused[0x6a]; // zero
77   struct { unsigned char map2[3]; } bam2[35];
78   unsigned char unused2[0x2d]; // zer0
79} D71_HEADER;
80
81static D64_HEADER d64_header={
82   18,1,'A',
83   0, // 1571 0x80
84   { { 0 } },
85   { '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0',
86     '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0' },
87   { 0xa0, 0xa0 }, { 0xa0, 0xa0 } , 0xa0, { '2', 'A' } , { '\xa0','\xa0','\xa0','\xa0' },
88};
89
90typedef struct {
91   unsigned char not_usable[2];
92   unsigned char type;
93#define FILE_TYPE_DEL 0
94#define FILE_TYPE_SEQ 1
95#define FILE_TYPE_PRG 2
96#define FILE_TYPE_USR 3
97#define FILE_TYPE_REL 4
98#define FILE_TYPE_MASK 0x3f
99   unsigned char track, sector, name[0x10];
100   unsigned char rel_track, rel_sector, rel_length;
101   unsigned char unused[4];
102   unsigned char replace_track, replace_sector;
103   littleuword blocks;
104} D64_ENTRY;
105
106typedef union {
107   struct {
108      unsigned char track, sector; //linkage to next track=0 for last
109   } linkage;
110   D64_ENTRY entry[8];
111} D64_DIRECTORY;
112
113typedef struct {
114   unsigned char track, sector, // of next directory
115      format, unused;
116   unsigned char name[0x12], id[2], filler2, version[2], filler3[2];
117   unsigned char unused1[227]; // zero
118} D81_HEADER;
119
120static D81_HEADER d81_header={
121   40,3,'D',
122   0,
123   { '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0',
124     '\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0','\xa0', 0xa0, 0xa0 },
125   { 0xa0, 0xa0 } , 0xa0, { '3', 'D' } , { '\xa0','\xa0' },
126};
127
128typedef struct {
129   unsigned char track, sector;
130   unsigned char version, complement;
131   unsigned char id[2], iobyte, autoloader;
132   unsigned char reserved[8];
133   struct { unsigned char free, map[5]; } bam[40];
134} D81_BAM;
135
136static D81_BAM d81_bam={
137   40, 2,0x44, 0xbb,
138};
139
140#define D71_MAX_TRACKS 70
141
142int d71_sectors_per_track[] =
143{
144   21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
145   19, 19, 19, 19, 19, 19, 19,
146   18, 18, 18, 18, 18, 18,
147   17, 17, 17, 17, 17,
148   21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21,
149   19, 19, 19, 19, 19, 19, 19,
150   18, 18, 18, 18, 18, 18,
151   17, 17, 17, 17, 17
152};
153
154static int d71_offset[D71_MAX_TRACKS+1];         /* offset of begin of track in d64 file */
155
156/* must be called before other functions */
157void d64_open_helper (void)
158{
159   int i;
160
161   d64_offset[0] = 0;
162   for (i = 1; i <= D64_MAX_TRACKS; i++)
163      d64_offset[i] = d64_offset[i - 1] + d64_sectors_per_track[i - 1] * 256;
164
165   d71_offset[0] = 0;
166   for (i = 1; i <= D71_MAX_TRACKS; i++)
167      d71_offset[i] = d71_offset[i - 1] + d71_sectors_per_track[i - 1] * 256;
168}
169
170/* calculates offset to beginning of d64 file for sector beginning */
171static int d64_tracksector2offset (int track, int sector)
172{
173   return d64_offset[track - 1] + sector * 256;
174}
175
176/* calculates offset to beginning of d71 file for sector beginning */
177int d71_tracksector2offset (int track, int sector)
178{
179   return d71_offset[track - 1] + sector * 256;
180}
181
182/* calculates offset to beginning of d71 file for sector beginning */
183int d81_tracksector2offset (int track, int sector)
184{
185   return ((track - 1)*20*2 + sector )* 256;
186}
187
188static void cbm_filename_to_cstring(unsigned char *cbmstring, int size, unsigned char* cstring)
189{
190   int i;
191   for (i=0; (i<size)&&(cbmstring[i]!=0xa0); i++) cstring[i]=cbmstring[i];
192   cstring[i]=0;
193}
194
195int cbm_compareNames (const unsigned char *left, const unsigned char *right)
196{
197   int i;
198
199   for (i = 0; i < 16; i++)
200   {
201      if ((left[i] == '*') || (right[i] == '*'))
202         return 1;
203
204      if (left[i] == right[i]) {
205         if (left[i]==0) return 1;
206         continue;
207      }
208      if ((left[i] == 0xa0) && (right[i] == 0))
209         return 1;
210      if ((right[i] == 0xa0) && (left[i] == 0))
211         return 1;
212      return 0;
213   }
214   return 1;
215}
216
217typedef struct _d64_image {
218   imgtool_image base;
219   imgtool_stream *file_handle;
220   int d64;
221   int x64; // x64 header at the beginning
222   int d71; // c128d/1571 diskette
223   int d81; // c65/1581/1565 diskette
224
225   int (*get_offset)(int track, int sector);
226   void (*alloc_sector)(struct _d64_image *image, int *track, int *sector);
227   void (*free_sector)(struct _d64_image *image, int track, int sector);
228   struct { int track, sector; } directory;
229   int bam_bytes_dir_track;
230
231   int tracks; //35 or 40 tracks
232   int crc; // crc data at the end of file
233   int size;
234   int modified;
235   unsigned char *realimage; //inclusive x64 header
236   unsigned char *data; // pointer to start of d64 image
237} d64_image;
238
239typedef struct {
240   imgtool_directory base;
241   d64_image *image;
242   int track, sector;
243   int offset;
244} d64_iterator;
245
246static void d64_alloc_sector(struct _d64_image *image, int *track, int *sector)
247{
248   static int tracks[35];
249   int i, j;
250   D64_HEADER *header=(D64_HEADER*)
251      (image->data+image->get_offset(image->directory.track,image->directory.sector));
252
253   // this contains the tracks for the search strategy for free sectors
254   for (i=0,j=17; i<35; i+=2,j--) tracks[i]=j;
255   for (i=1,j=19; i<35; i+=2,j++) tracks[i]=j;
256   tracks[35-1]=18;
257
258   for (i=0; i<35; i++) {
259      *track=tracks[i];
260      if (header->bam[*track-1].free) {
261         for (j=0,*sector=0;j<3; j++) {
262            int mask=1;
263            for (; mask<=0x80; mask<<=1, (*sector)++) {
264               if (header->bam[*track-1].map[j]&mask) {
265                  header->bam[*track-1].map[j]&=~mask;
266                  header->bam[*track-1].free--;
267                  return;
268               }
269            }
270         }
271      }
272   }
273}
274
275static void d64_free_sector(struct _d64_image *image, int track, int sector)
276{
277   D64_HEADER *header=(D64_HEADER*)
278      (image->data+image->get_offset(image->directory.track,image->directory.sector));
279   int i=sector>>3;
280   int mask=1<<(sector&7);
281   header->bam[track-1].free++;
282   header->bam[track-1].map[i]|=mask;
283}
284
285static void d71_alloc_sector(struct _d64_image *image, int *track, int *sector)
286{
287   static int tracks[70];
288   int i, j;
289   D64_HEADER *header=(D64_HEADER*)
290      (image->data+image->get_offset(image->directory.track,image->directory.sector));
291   D71_HEADER *header2=(D71_HEADER*)
292      (image->data+image->get_offset(image->directory.track+35,image->directory.sector));
293
294   // this contains the tracks for the search strategy for free sectors
295   for (i=0,j=17; i<35; i+=4,j--) { tracks[i]=j; tracks[i+1]=j+35; }
296   for (i=2,j=19; i<35; i+=4,j++) { tracks[i]=j; tracks[i+1]=j+35; }
297   tracks[70-1]=18;
298
299   for (i=0; i<35; i++) {
300      *track=tracks[i];
301      if (*tracks<=35) {
302         if (header->bam[*track-1].free) {
303            for (j=0,*sector=0;j<3; j++) {
304               int mask=1;
305               for (; mask<=0x80; mask<<=1, (*sector)++) {
306                  if (header->bam[*track-1].map[j]&mask) {
307                     header->bam[*track-1].map[j]&=~mask;
308                     header->bam[*track-1].free--;
309                     return;
310                  }
311               }
312            }
313         }
314      } else {
315         if (header->free2[*track-36]) {
316            for (j=0,*sector=0;j<3; j++) {
317               int mask=1;
318               for (; mask<=0x80; mask<<=1, (*sector)++) {
319                  if (header2->bam2[*track-36].map2[j]&mask) {
320                     header2->bam2[*track-36].map2[j]&=~mask;
321                     header->free2[*track-36]--;
322                     return;
323                  }
324               }
325            }
326         }
327      }
328   }
329}
330
331static void d71_free_sector(struct _d64_image *image, int track, int sector)
332{
333   D64_HEADER *header=(D64_HEADER*)
334      (image->data+image->get_offset(image->directory.track,image->directory.sector));
335   D71_HEADER *header2=(D71_HEADER*)
336      (image->data+image->get_offset(image->directory.track+35,image->directory.sector));
337   int i=sector>>3;
338   int mask=1<<(sector&7);
339   if (track<=35) {
340      header->bam[track-1].free++;
341      header->bam[track-1].map[i]|=mask;
342   } else {
343      header->free2[track-36]++;
344      header2->bam2[track-36].map2[i]|=mask;
345   }
346}
347
348static void d81_alloc_sector(struct _d64_image *image, int *track, int *sector)
349{
350   static int tracks[80];
351   int i, j;
352   D81_BAM *bam[2];
353   bam[0] = (D81_BAM*) (image->data + image->get_offset(image->directory.track, image->directory.sector+1)),
354   bam[1] = (D81_BAM*) (image->data + image->get_offset(image->directory.track, image->directory.sector+1));
355   
356   /* this contains the tracks for the search strategy for free sectors */
357   for (i=0,j=image->directory.track-1; j>0; i++,j--) tracks[i]=j;
358   for (j=image->directory.track+1;j<80;i++,j++) tracks[i]=j;
359   tracks[i]=image->directory.track;
360
361   for (i=0; i<80; i++) {
362      D81_BAM *b;
363      *track=tracks[i];
364      if (*track<=40) b=bam[0];
365      else b=bam[1];
366      if (b->bam[*track-1].free) {
367         for (j=0,*sector=0;j<6; j++) {
368            int mask=0;
369            for (; mask<=0x80; mask<<=1, (*sector)++) {
370               if (b->bam[*track-1].map[j]&mask) {
371                  b->bam[*track-1].map[j]&=~mask;
372                  b->bam[*track-1].free--;
373                  return;
374               }
375            }
376         }
377      }
378   }
379}
380
381static void d81_free_sector(struct _d64_image *image, int track, int sector)
382{
383   D81_BAM *bam;
384   int i=sector>>3;
385   int mask=1<<(sector&7);
386
387   if (track<=40) {
388      bam=(D81_BAM*)
389         (image->data
390          +image->get_offset(image->directory.track,
391                        image->directory.sector+1));
392   } else {
393      track-=40;
394      bam=(D81_BAM*)
395         (image->data
396          +image->get_offset(image->directory.track,
397                        image->directory.sector+2));
398   }
399   
400   bam->bam[track-1].free++;
401   bam->bam[track-1].map[i]|=mask;
402}
403
404int d64_getcrc(d64_image *image, int track, int sector)
405{
406   int pos=d64_tracksector2offset(track, sector)>>8;
407   if (!image->crc) return 0;
408   return image->data[d64_tracksector2offset(image->tracks+1,0)+pos];
409}
410
411static D64_ENTRY *d64_get_free_entry(d64_image *image)
412{
413   D64_HEADER *header;
414   D64_DIRECTORY *dir = (D64_DIRECTORY*)
415      (image->data+image->get_offset (image->directory.track, image->directory.sector));
416
417   int i, mask, s;
418
419   while ((dir->linkage.track >= 1) && (dir->linkage.track <= image->tracks))
420   {
421      dir=(D64_DIRECTORY*)
422         (image->data+image->get_offset(dir->linkage.track, dir->linkage.sector));
423      for (i = 0; i < 8; i ++)
424      {
425         if (!(dir->entry[i].type & 0x80))
426            return dir->entry + i;
427      }
428   }
429
430   // add new sector to directory
431    header = (D64_HEADER*)
432      (image->data+image->get_offset (image->directory.track, image->directory.sector));
433
434   if (header->bam[image->directory.track-1].free) {
435      for (i=0, s=0; i<image->bam_bytes_dir_track; i++) {
436         for (mask=0x80; mask>0; mask>>=1, s++) {
437            if (header->bam[image->directory.track-1].map[i]&mask) {
438               header->bam[image->directory.track-1].free--;
439               header->bam[image->directory.track-1].map[i]&=~mask;
440               dir->linkage.track=image->directory.track-1;
441               dir->linkage.sector=s;
442               return (D64_ENTRY*)(image->data+image->get_offset(image->directory.track, s));
443            }
444         }
445      }
446   }
447   // no sector in directory track free
448   return NULL;
449}
450
451/* searches program with given name in directory */
452static D64_ENTRY *d64_image_findfile (d64_image *image, const unsigned char *name)
453{
454   int i;
455
456   D64_DIRECTORY *dir = (D64_DIRECTORY*)
457      (image->data+image->get_offset (image->directory.track, image->directory.sector));
458
459   while ((dir->linkage.track >= 1) && (dir->linkage.track <= image->tracks))
460   {
461      dir=(D64_DIRECTORY*)
462         (image->data+image->get_offset(dir->linkage.track, dir->linkage.sector));
463      for (i = 0; i < 8; i ++)
464      {
465         if (dir->entry[i].type & 0x80)
466         {
467            if (mame_stricmp ((char *) name, (char *) "*") == 0)
468               return dir->entry + i;
469            if (cbm_compareNames (name, dir->entry[i].name))
470               return dir->entry + i;
471         }
472      }
473   }
474   return NULL;
475}
476
477#if 0
478static int d64_filesize(d64_image *image, D64_ENTRY *entry)
479{
480   int size = 0;
481   int i=image->get_offset(entry->track, entry->sector);
482   
483   while (image->data[i] != 0)
484   {
485      size += 254;
486      i = image->get_offset (image->data[i], image->data[i + 1]);
487   }
488   size += image->data[i + 1]-1;
489   return size;
490}
491#endif
492
493static int d64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
494static void d64_image_exit(imgtool_image *img);
495static void d64_image_info(imgtool_image *img, char *string, const int len);
496static int d64_image_beginenum(imgtool_image *img, imgtool_directory **outenum);
497static int d64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent);
498static void d64_image_closeenum(imgtool_directory *enumeration);
499static size_t d64_image_freespace(imgtool_image *img);
500static int d64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf);
501static int d64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_);
502static int d64_image_deletefile(imgtool_image *img, const char *fname);
503static int d64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
504
505static int x64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
506static int x64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
507
508static int d71_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
509static size_t d71_image_freespace(imgtool_image *img);
510static int d71_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
511
512static int d81_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg);
513static void d81_image_info(imgtool_image *img, char *string, const int len);
514static size_t d81_image_freespace(imgtool_image *img);
515static int d81_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_);
516
517static int d64_read_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, void *buffer, int length);
518static int d64_write_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, const void *buffer, int length);
519
520static struct OptionTemplate d64_createopts[] =
521{
522   { "label",   NULL, IMGOPTION_FLAG_TYPE_STRING | IMGOPTION_FLAG_HASDEFAULT,   0,      0,      NULL   },   /* [3] */
523   { NULL, NULL, 0, 0, 0, 0 }
524};
525
526#define D64_CREATEOPTION_LABEL         0
527
528IMAGEMODULE(
529   d64,
530   "Commodore SX64/VC1541/2031/1551 Diskette",   /* human readable name */
531   "d64",                        /* file extension */
532   NULL,                        /* crcfile */
533   NULL,                        /* crc system name */
534   EOLN_CR,                     /* eoln */
535   0,                           /* flags */
536   d64_image_init,            /* init function */
537   d64_image_exit,            /* exit function */
538   d64_image_info,      /* info function */
539   d64_image_beginenum,         /* begin enumeration */
540   d64_image_nextenum,         /* enumerate next */
541   d64_image_closeenum,         /* close enumeration */
542   d64_image_freespace,          /*  free space on image    */
543   d64_image_readfile,         /* read file */
544   d64_image_writefile,         /* write file */
545   d64_image_deletefile,         /* delete file */
546   d64_image_create,            /* create image */
547   d64_read_sector,
548   d64_write_sector,
549   NULL,                        /* file options */
550   d64_createopts                  /* create options */
551)
552
553IMAGEMODULE(
554   x64,
555   "Commodore VC1541 Diskette",   /* human readable name */
556   "x64",                        /* file extension */
557   NULL,                        /* crcfile */
558   NULL,                        /* crc system name */
559   EOLN_CR,                     /* eoln */
560   0,                           /* flags */
561   x64_image_init,            /* init function */
562   d64_image_exit,            /* exit function */
563   d64_image_info,      /* info function */
564   d64_image_beginenum,         /* begin enumeration */
565   d64_image_nextenum,         /* enumerate next */
566   d64_image_closeenum,         /* close enumeration */
567   d64_image_freespace,          /* free space on image    */
568   d64_image_readfile,         /* read file */
569   d64_image_writefile,         /* write file */
570   d64_image_deletefile,         /* delete file */
571   x64_image_create,            /* create image */
572   d64_read_sector,
573   d64_write_sector,
574   NULL,                        /* file options */
575   d64_createopts                  /* create options */
576)
577
578IMAGEMODULE(
579   d71,
580   "Commodore 128D/1571 Diskette",   /* human readable name */
581   "d71",                        /* file extension */
582   NULL,                        /* crcfile */
583   NULL,                        /* crc system name */
584   EOLN_CR,                     /* eoln */
585   0,                           /* flags */
586   d71_image_init,            /* init function */
587   d64_image_exit,            /* exit function */
588   d64_image_info,      /* info function */
589   d64_image_beginenum,         /* begin enumeration */
590   d64_image_nextenum,         /* enumerate next */
591   d64_image_closeenum,         /* close enumeration */
592   d71_image_freespace,          /*  free space on image    */
593   d64_image_readfile,         /* read file */
594   d64_image_writefile,         /* write file */
595   d64_image_deletefile,         /* delete file */
596   d71_image_create,            /* create image */
597   d64_read_sector,
598   d64_write_sector,
599   NULL,                        /* file options */
600   d64_createopts                  /* create options */
601)
602
603IMAGEMODULE(
604   d81,
605   "Commodore 65/1565/1581 Diskette",   /* human readable name */
606   "d81",                        /* file extension */
607   NULL,                        /* crcfile */
608   NULL,                        /* crc system name */
609   EOLN_CR,                     /* eoln */
610   0,                           /* flags */
611   d81_image_init,            /* init function */
612   d64_image_exit,            /* exit function */
613   d81_image_info,      /* info function */
614   d64_image_beginenum,         /* begin enumeration */
615   d64_image_nextenum,         /* enumerate next */
616   d64_image_closeenum,         /* close enumeration */
617   d81_image_freespace,          /*  free space on image    */
618   d64_image_readfile,         /* read file */
619   d64_image_writefile,         /* write file */
620   d64_image_deletefile,         /* delete file */
621   d81_image_create,            /* create image */
622   d64_read_sector,
623   d64_write_sector,
624   NULL,                        /* file options */
625   d64_createopts                  /* create options */
626)
627
628static int d64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
629{
630   d64_image *image;
631
632   d64_open_helper();
633   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
634   if (!image) return IMGTOOLERR_OUTOFMEMORY;
635
636   memset(image, 0, sizeof(d64_image));
637   image->base.module = mod;
638   image->size=stream_size(f);
639   image->file_handle=f;
640   image->get_offset=d64_tracksector2offset;
641   image->alloc_sector=d64_alloc_sector;
642   image->free_sector=d64_free_sector;
643   image->directory.track=18;image->directory.sector=0;
644   image->bam_bytes_dir_track=3;
645   image->d64=1;
646
647   switch (image->size) {
648   case 174848: image->tracks=35;break;
649   case 175531: image->tracks=35;image->crc=1;break;
650   case 196608: image->tracks=40;break;
651   case 197376: image->tracks=40;image->crc=1;break;
652   default:
653      free(image);
654      *outimg=NULL;
655      return IMGTOOLERR_CORRUPTIMAGE;
656   }
657
658   image->realimage = (unsigned char *) malloc(image->size);
659   image->data = image->realimage;
660   if ( (!image->data)
661       ||(stream_read(f, image->data, image->size)!=image->size) ) {
662      free(image);
663      *outimg=NULL;
664      return IMGTOOLERR_OUTOFMEMORY;
665   }
666
667   return 0;
668}
669
670static int x64_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
671{
672   d64_image *image;
673
674   d64_open_helper();
675   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
676   if (!image) return IMGTOOLERR_OUTOFMEMORY;
677
678   memset(image, 0, sizeof(d64_image));
679   image->base.module = mod;
680   image->size=stream_size(f);
681   image->file_handle=f;
682   image->get_offset=d64_tracksector2offset;
683   image->alloc_sector=d64_alloc_sector;
684   image->free_sector=d64_free_sector;
685   image->directory.track=18;image->directory.sector=0;
686   image->bam_bytes_dir_track=3;
687   image->x64=1;
688   switch (image->size) {
689   case 174848+0x40: image->tracks=35;break;
690   case 175531+0x40: image->tracks=35;image->crc=1;break;
691   case 196608+0x40: image->tracks=40;break;
692   case 197376+0x40: image->tracks=40;image->crc=1;break;
693   default:
694      free(image);
695      *outimg=NULL;
696      return IMGTOOLERR_CORRUPTIMAGE;
697   }
698
699   image->realimage = (unsigned char *) malloc(image->size);
700   image->data = image->realimage+0x40;
701   if ( (!image->realimage)
702       ||(stream_read(f, image->realimage, image->size)!=image->size) ) {
703      free(image);
704      *outimg=NULL;
705      return IMGTOOLERR_OUTOFMEMORY;
706   }
707
708   return 0;
709}
710
711static int d71_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
712{
713   d64_image *image;
714
715   d64_open_helper();
716   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
717   if (!image) return IMGTOOLERR_OUTOFMEMORY;
718
719   memset(image, 0, sizeof(d64_image));
720   image->base.module = mod;
721   image->size=stream_size(f);
722   image->file_handle=f;
723   image->get_offset=d71_tracksector2offset;
724   image->alloc_sector=d71_alloc_sector;
725   image->free_sector=d71_free_sector;
726   image->directory.track=18;image->directory.sector=0;
727   image->d71=1;
728   image->tracks=70;
729
730   image->realimage = (unsigned char *) malloc(image->size);
731   image->data = image->realimage;
732   if ( (!image->data)
733       ||(stream_read(f, image->data, image->size)!=image->size) ) {
734      free(image);
735      *outimg=NULL;
736      return IMGTOOLERR_OUTOFMEMORY;
737   }
738
739   return 0;
740}
741
742static int d81_image_init(const imgtool_module *mod, imgtool_stream *f, imgtool_image **outimg)
743{
744   d64_image *image;
745
746   d64_open_helper();
747   image=*(d64_image**)outimg=(d64_image *) malloc(sizeof(d64_image));
748   if (!image) return IMGTOOLERR_OUTOFMEMORY;
749
750   memset(image, 0, sizeof(d64_image));
751   image->base.module = mod;
752   image->size=stream_size(f);
753   image->get_offset=d81_tracksector2offset;
754   image->alloc_sector=d81_alloc_sector;
755   image->free_sector=d81_free_sector;
756   image->directory.track=40;image->directory.sector=0;
757   image->d81=1;
758   image->tracks=80;
759   image->bam_bytes_dir_track=6;
760   image->file_handle=f;
761
762   image->realimage = (unsigned char *) malloc(image->size);
763   image->data = image->realimage;
764   if ( (!image->data)
765       ||(stream_read(f, image->data, image->size)!=image->size) ) {
766      free(image);
767      *outimg=NULL;
768      return IMGTOOLERR_OUTOFMEMORY;
769   }
770
771   return 0;
772}
773
774static void d64_image_exit(imgtool_image *img)
775{
776   d64_image *image=(d64_image*)img;
777   if (image->modified) {
778      stream_seek(image->file_handle, 0, SEEK_SET);
779      stream_write(image->file_handle, image->realimage, image->size);
780   }
781   stream_close(image->file_handle);
782   free(image->realimage);
783   free(image);
784}
785
786static void d64_image_info(imgtool_image *img, char *string, const int len)
787{
788   d64_image *image=(d64_image*)img;
789   char name[17]={ 0 };
790
791   int pos=image->get_offset(image->directory.track,image->directory.sector);
792
793   cbm_filename_to_cstring((unsigned char *)image->data+pos+0x90, 16,
794      (unsigned char*)name);
795   if ((image->d64)||(image->x64)) {
796      sprintf(string, "%d tracks%s\n%-16s %c%c %c%c",
797            image->tracks, image->crc?" with crc":"",
798            name,
799            image->data[pos + 162], image->data[pos + 163],
800            image->data[pos + 165], image->data[pos + 166] );
801   } else {
802      sprintf(string, "%-16s %c%c %c%c",
803            name,
804            image->data[pos + 162], image->data[pos + 163],
805            image->data[pos + 165], image->data[pos + 166] );
806   }
807}
808
809static void d81_image_info(imgtool_image *img, char *string, const int len)
810{
811   d64_image *image=(d64_image*)img;
812   char name[17]={ 0 };
813
814   int pos=image->get_offset(image->directory.track,image->directory.sector);
815
816   cbm_filename_to_cstring((unsigned char *)image->data+pos+4, 16,
817      (unsigned char *)name);
818   sprintf(string, "%d tracks%s\n%-16s %c%c %c%c",
819         image->tracks, image->crc?" with crc":"",
820         name,
821         image->data[pos + 22], image->data[pos + 23],
822         image->data[pos + 25], image->data[pos + 26] );
823}
824
825static int d64_image_beginenum(imgtool_image *img, imgtool_directory **outenum)
826{
827   d64_image *image=(d64_image*)img;
828   d64_iterator *iter;
829   int pos;
830
831   iter=*(d64_iterator**)outenum = (d64_iterator *) malloc(sizeof(d64_iterator));
832   if (!iter) return IMGTOOLERR_OUTOFMEMORY;
833
834   iter->base.module = img->module;
835
836   iter->image=image;
837   pos = image->get_offset (image->directory.track, image->directory.sector);
838   iter->track = iter->image->data[pos];
839   iter->sector = iter->image->data[pos + 1];
840   iter->offset = 2;
841   return 0;
842}
843
844static int d64_image_nextenum(imgtool_directory *enumeration, imgtool_dirent *ent)
845{
846   d64_iterator *iter=(d64_iterator*)enumeration;
847   int pos;
848
849   ent->corrupt=0;
850   ent->eof=0;
851   
852   while ((iter->track >= 1) && (iter->track <= iter->image->tracks)) //safer
853//   while (iter->track != 0)
854   {
855      pos = iter->image->get_offset(iter->track, iter->sector);
856      for (; iter->offset<256; iter->offset += 32)
857      {
858         if (iter->image->data[pos + iter->offset] & 0x80)
859         {
860            cbm_filename_to_cstring(
861               (unsigned char*)iter->image->data+pos+iter->offset+3,
862               16, (unsigned char *)ent->fname);
863
864            ent->filesize=iter->image->data[pos+iter->offset+28]
865               +(iter->image->data[pos+iter->offset+29]<<8); // in blocks
866
867            if (ent->attr) {
868               switch (iter->image->data[pos+iter->offset]&FILE_TYPE_MASK) {
869               case FILE_TYPE_DEL: sprintf(ent->attr,"DEL");break;
870               case FILE_TYPE_SEQ: sprintf(ent->attr,"SEQ");break;
871               case FILE_TYPE_PRG: sprintf(ent->attr,"PRG");break;
872               case FILE_TYPE_USR: sprintf(ent->attr,"USR");break;
873               case FILE_TYPE_REL: sprintf(ent->attr,"REL");break;
874               default: sprintf(ent->attr,"unknown!");break;
875               }
876            }
877            iter->offset+=32;
878            return 0;
879         }
880      }
881      iter->track = iter->image->data[pos];
882      iter->sector = iter->image->data[pos + 1];
883      iter->offset = 2;
884   }
885
886   ent->eof=1;
887   return 0;
888}
889
890static void d64_image_closeenum(imgtool_directory *enumeration)
891{
892   free(enumeration);
893}
894
895static size_t d64_image_freespace(imgtool_image *img)
896{
897   d64_image *image=(d64_image*)img;
898   int i, j, pos;
899   size_t blocksfree = 0;
900
901   pos = image->get_offset(image->directory.track, image->directory.sector);
902   blocksfree = 0;
903   for (j = 1, i = 4; j <= 35; j++, i += 4) // no more room for BAM!
904   {
905      blocksfree += image->data[pos + i];
906   }
907
908   return blocksfree;
909}
910
911static size_t d71_image_freespace(imgtool_image *img)
912{
913   d64_image *image=(d64_image*)img;
914   int i, j, pos;
915   size_t blocksfree = 0;
916
917   pos = image->get_offset(image->directory.track, image->directory.sector);
918   blocksfree = 0;
919   for (j = 1, i = 4; j <= 35; j++, i += 4)
920   {
921      blocksfree += image->data[pos + i];
922   }
923   for (i = 221; j <= 70; j++, i ++)
924   {
925      blocksfree += image->data[pos + i];
926   }
927
928   return blocksfree;
929}
930
931static size_t d81_image_freespace(imgtool_image *img)
932{
933   d64_image *image=(d64_image*)img;
934   int j,k;
935   size_t blocksfree = 0;
936
937   for (k=1; k<=2; k++) {
938      D81_BAM *bam=(D81_BAM*)(image->data+image->get_offset(40,k));
939      for (j = 1; j <= 40; j++)
940      {
941         blocksfree += bam->bam[j-1].free;
942      }
943   }
944
945   return blocksfree;
946}
947
948static int d64_image_readfile(imgtool_image *img, const char *fname, imgtool_stream *destf)
949{
950   d64_image *image=(d64_image*)img;
951   int pos;
952   D64_ENTRY *entry;
953
954   if ((entry=d64_image_findfile(image, (const unsigned char *)fname))==NULL )
955      return IMGTOOLERR_MODULENOTFOUND;
956
957   pos = image->get_offset(entry->track, entry->sector);
958
959   while (image->data[pos]!=0) {
960      if (stream_write(destf, image->data+pos+2, 254)!=254)
961         return IMGTOOLERR_WRITEERROR;
962     
963      pos = image->get_offset (image->data[pos + 0], image->data[pos + 1]);
964   }
965   if (image->data[pos+1]-1>0) {
966      if (stream_write(destf, image->data+pos+2, image->data[pos+1]-1)!=image->data[pos+1]-1)
967         return IMGTOOLERR_WRITEERROR;
968   }
969
970   return 0;
971}
972
973static int d64_image_writefile(imgtool_image *img, const char *fname, imgtool_stream *sourcef, const ResolvedOption *options_)
974{
975   d64_image *image=(d64_image*)img;
976   int fsize, pos, i, b, freespace;
977   int track, sector;
978   D64_ENTRY *entry;
979
980   fsize=stream_size(sourcef)+1;
981
982   imgtool_partition_get_free_space(img, &freespace);
983
984   if ((entry=d64_image_findfile(image, (const unsigned char *)fname))!=NULL ) {
985      /* overriding */
986      if ((freespace + GET_UWORD(entry->blocks))*254<fsize)
987         return IMGTOOLERR_NOSPACE;
988      track=entry->track;
989      sector=entry->sector;
990     
991      while (track!=0) {
992         image->free_sector(image, track, sector);
993         pos = image->get_offset(track, sector);
994         track=image->data[pos];
995         sector=image->data[pos+1];
996      }
997   } else {
998      if (freespace*254<fsize) return IMGTOOLERR_NOSPACE;
999      // search free entry
1000      entry=d64_get_free_entry(image);
1001   }
1002
1003   entry->type=FILE_TYPE_PRG|0x80;
1004   memset(entry->name, 0xa0, sizeof(entry->name));
1005   memcpy(entry->name, fname, strlen(fname));
1006
1007   image->alloc_sector(image, &track, &sector);
1008   entry->track=track;
1009   entry->sector=sector;
1010   pos = image->get_offset(track, sector);
1011
1012   for (i = 0, b=0; i + 254 < fsize; i += 254, b++)
1013   {
1014      if (stream_read(sourcef, image->data+pos+2, 254)!=254)
1015         return IMGTOOLERR_READERROR;
1016     
1017      image->alloc_sector(image, &track, &sector);
1018      image->data[pos]=track;
1019      image->data[pos+1]=sector;
1020      pos = image->get_offset (track, sector);
1021   }
1022   b++;
1023   image->data[pos]=0;
1024   image->data[pos+1]=fsize-i;
1025   if (fsize-i-1>0) {
1026      if (stream_read(sourcef, image->data+pos+2, fsize-i-1)!=fsize-i-1)
1027         return IMGTOOLERR_READERROR;
1028   }
1029   image->data[pos+2+fsize-i]=0;
1030   
1031   SET_UWORD(entry->blocks, b);
1032   image->modified=1;
1033
1034   return 0;
1035}
1036
1037static int d64_image_deletefile(imgtool_image *img, const char *fname)
1038{
1039   d64_image *image=(d64_image*)img;
1040   int pos;
1041   int sector, track;
1042   D64_ENTRY *entry;
1043
1044   if ((entry=d64_image_findfile(image, (const unsigned char *)fname))==NULL )
1045      return IMGTOOLERR_MODULENOTFOUND;
1046
1047   track=entry->track;
1048   sector=entry->sector;
1049
1050   while (track!=0) {
1051      image->free_sector(image, track, sector);
1052      pos = image->get_offset(track, sector);
1053      track=image->data[pos];
1054      sector=image->data[pos+1];
1055   }
1056
1057   image->modified=1;
1058   return 0;
1059}
1060
1061static int d64_read_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, void *buffer, int length)
1062{
1063   /* not yet implemented */
1064   assert(0);
1065   return IMGTOOLERR_UNEXPECTED;
1066}
1067
1068static int d64_write_sector(imgtool_image *img, UINT8 head, UINT8 track, UINT8 sector, int offset, const void *buffer, int length)
1069{
1070   /* not yet implemented */
1071   assert(0);
1072   return IMGTOOLERR_UNEXPECTED;
1073}
1074
1075static int d64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1076{
1077   unsigned char sector[0x100]={0};
1078   int tracks=35;
1079   int crc=0;
1080   int t,s,i;
1081
1082   for (t=1; t<=tracks; t++) {
1083      for (s=0; s<d64_sectors_per_track[t-1]; s++) {
1084         if ((t==18)&&(s==0)) {
1085            for (i=1; i<=35; i++) {
1086               d64_header.bam[i-1].free=d64_sectors_per_track[i-1];
1087               d64_header.bam[i-1].map[0]=0xff;
1088               d64_header.bam[i-1].map[1]=0xff;
1089               switch (d64_header.bam[i-1].free) {
1090               case 17: d64_header.bam[i-1].map[2]=1;break;
1091               case 18: d64_header.bam[i-1].map[2]=3;break;
1092               case 19: d64_header.bam[i-1].map[2]=7;break;
1093               case 21: d64_header.bam[i-1].map[2]=0x1f;break;
1094               }
1095               if (i==18) { // allocate the 2 directory sectors
1096                  d64_header.bam[i-1].free-=2;
1097                  d64_header.bam[i-1].map[0]&=~3;
1098               }
1099            }
1100            //d64_header.name=0xa0;
1101            //d64_header.id=0xa0;
1102            if (stream_write(f, &d64_header, sizeof(d64_header)) != sizeof(d64_header))
1103               return  IMGTOOLERR_WRITEERROR;
1104         } else {
1105            if (stream_write(f, &sector, sizeof(sector)) != sizeof(sector))
1106               return  IMGTOOLERR_WRITEERROR;
1107         }
1108      }
1109   }
1110   if (crc) {
1111      for (t=1; t<=tracks; t++) {
1112         if (stream_write(f, &d64_header, d64_sectors_per_track[t-1])
1113            != d64_sectors_per_track[t-1])
1114            return  IMGTOOLERR_WRITEERROR;
1115         }
1116   }
1117   return 0;
1118}
1119
1120static int x64_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1121{
1122   struct {
1123      unsigned char data[0x40];
1124   } x64_header={
1125      { 0x43, 0x15, 0x41, 0x64,
1126        0x01, 0x02, 0x01, 0x23,
1127        0x01
1128      }
1129   };
1130   if (stream_write(f, &x64_header, sizeof(x64_header)) != sizeof(x64_header))
1131      return  IMGTOOLERR_WRITEERROR;
1132
1133   d64_image_create(mod, f, options_);
1134   return 0;
1135}
1136
1137static int d71_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1138{
1139   D71_HEADER d71_header= { { 0 } };
1140   unsigned char sector[0x100]={0};
1141   int t,s,i;
1142
1143   for (t=1; t<=70; t++) {
1144      for (s=0; s<d71_sectors_per_track[t-1]; s++) {
1145         if ((t==18)&&(s==0)) {
1146            d64_header.doublesided=0x80;
1147            for (i=1; i<=35; i++) {
1148               d64_header.bam[i-1].free=d71_sectors_per_track[i-1];
1149               d64_header.bam[i-1].map[0]=0xff;
1150               d64_header.bam[i-1].map[1]=0xff;
1151               switch (d64_header.bam[i-1].free) {
1152               case 17: d64_header.bam[i-1].map[2]=1;break;
1153               case 18: d64_header.bam[i-1].map[2]=3;break;
1154               case 19: d64_header.bam[i-1].map[2]=7;break;
1155               case 21: d64_header.bam[i-1].map[2]=0x1f;break;
1156               }
1157               if (i==18) { // allocate the 2 directory sectors
1158                  d64_header.bam[i-1].free-=2;
1159                  d64_header.bam[i-1].map[0]&=~3;
1160               }
1161            }
1162            for (;i<=70;i++) {
1163               if (i!=18+35)
1164                  d64_header.free2[i-36]=d71_sectors_per_track[i-1];
1165               else
1166                  d64_header.free2[i-36]=0;
1167            }
1168            //d64_header.name=0xa0;
1169            //d64_header.id=0xa0;
1170            if (stream_write(f, &d64_header, sizeof(d64_header)) != sizeof(d64_header))
1171               return  IMGTOOLERR_WRITEERROR;
1172         } else if ((t==35+18)&&(s==0)) {
1173            for (i=36;i<=70;i++) {
1174               if (i!=18+35) {
1175                  d71_header.bam2[i-36].map2[0]=0xff;
1176                  d71_header.bam2[i-36].map2[1]=0xff;
1177                  switch (d64_header.free2[i-36]) {
1178                  case 17: d71_header.bam2[i-36].map2[2]=1;break;
1179                  case 18: d71_header.bam2[i-36].map2[2]=3;break;
1180                  case 19: d71_header.bam2[i-36].map2[2]=7;break;
1181                  case 21: d71_header.bam2[i-36].map2[2]=0x1f;break;
1182                  }
1183               } else {
1184                  d71_header.bam2[i-36].map2[0]=0;
1185                  d71_header.bam2[i-36].map2[1]=0;
1186                  d71_header.bam2[i-36].map2[2]=0;
1187               }
1188            }
1189            if (stream_write(f, &d71_header, sizeof(d71_header))
1190               != sizeof(d71_header))
1191               return  IMGTOOLERR_WRITEERROR;
1192         } else {
1193            if (stream_write(f, &sector, sizeof(sector)) != sizeof(sector))
1194               return  IMGTOOLERR_WRITEERROR;
1195         }
1196      }
1197   }
1198   return 0;
1199}
1200
1201static int d81_image_create(const imgtool_module *mod, imgtool_stream *f, const ResolvedOption *options_)
1202{
1203   unsigned char sector[0x100]={0};
1204   unsigned char id[2]={'1','2'};
1205   int t,s,i;
1206
1207   for (t=1; t<=80; t++) {
1208      for (s=0; s<40; s++) {
1209         if ((t==40)&&(s==0)) {
1210            //d81_header.name=0xa0;
1211            d81_header.id[0]=id[0];
1212            d81_header.id[0]=id[1];
1213            if (stream_write(f, &d81_header, sizeof(d81_header)) != sizeof(d81_header))
1214               return  IMGTOOLERR_WRITEERROR;
1215         } else if ((t==40)&&(s==1)){
1216            d81_bam.id[0]=id[0];
1217            d81_bam.id[0]=id[1];
1218            for (i=1; i<=40; i++) {
1219               d81_bam.bam[i-1].free=40;
1220               d81_bam.bam[i-1].map[0]=0xff;
1221               d81_bam.bam[i-1].map[1]=0xff;
1222               d81_bam.bam[i-1].map[2]=0xff;
1223               d81_bam.bam[i-1].map[3]=0xff;
1224               d81_bam.bam[i-1].map[4]=0xff;
1225            }
1226            d81_bam.bam[40-1].free=36;
1227            d81_bam.bam[40-1].map[0]=0xf0;
1228            if (stream_write(f, &d81_bam, sizeof(d81_bam)) != sizeof(d81_bam))
1229               return  IMGTOOLERR_WRITEERROR;
1230            d81_bam.bam[40-1].free=40;
1231            d81_bam.bam[40-1].map[0]=0xff;
1232         } else if ((t==40)&&(s==2)){
1233            d81_bam.track=0;
1234            if (stream_write(f, &d81_bam, sizeof(d81_bam)) != sizeof(d81_bam))
1235               return  IMGTOOLERR_WRITEERROR;
1236         } else {
1237            if (stream_write(f, &sector, sizeof(sector)) != sizeof(sector))
1238               return  IMGTOOLERR_WRITEERROR;
1239         }
1240      }
1241   }
1242   return 0;
1243}

Previous 15994 Revisions Next


© 1998-2018 The MESS Team