use system's zlib
[picodrive.git] / pico / cart.c
1 /*\r
2  * PicoDrive\r
3  * (c) Copyright Dave, 2004\r
4  * (C) notaz, 2006-2010\r
5  *\r
6  * This work is licensed under the terms of MAME license.\r
7  * See COPYING file in the top-level directory.\r
8  */\r
9 \r
10 #include "pico_int.h"\r
11 #include "../cpu/debug.h"\r
12 #include "../unzip/unzip.h"\r
13 #include <zlib.h>\r
14 \r
15 \r
16 static int rom_alloc_size;\r
17 static const char *rom_exts[] = { "bin", "gen", "smd", "iso", "sms", "gg", "sg" };\r
18 \r
19 void (*PicoCartUnloadHook)(void);\r
20 void (*PicoCartMemSetup)(void);\r
21 \r
22 void (*PicoCartLoadProgressCB)(int percent) = NULL;\r
23 void (*PicoCDLoadProgressCB)(const char *fname, int percent) = NULL; // handled in Pico/cd/cd_file.c\r
24 \r
25 int PicoGameLoaded;\r
26 \r
27 static void PicoCartDetect(const char *carthw_cfg);\r
28 \r
29 /* cso struct */\r
30 typedef struct _cso_struct\r
31 {\r
32   unsigned char in_buff[2*2048];\r
33   unsigned char out_buff[2048];\r
34   struct {\r
35     char          magic[4];\r
36     unsigned int  unused;\r
37     unsigned int  total_bytes;\r
38     unsigned int  total_bytes_high; // ignored here\r
39     unsigned int  block_size;  // 10h\r
40     unsigned char ver;\r
41     unsigned char align;\r
42     unsigned char reserved[2];\r
43   } header;\r
44   unsigned int  fpos_in;  // input file read pointer\r
45   unsigned int  fpos_out; // pos in virtual decompressed file\r
46   int block_in_buff;      // block which we have read in in_buff\r
47   int pad;\r
48   int index[0];\r
49 }\r
50 cso_struct;\r
51 \r
52 static int uncompress_buf(void *dest, int destLen, void *source, int sourceLen)\r
53 {\r
54     z_stream stream;\r
55     int err;\r
56 \r
57     stream.next_in = (Bytef*)source;\r
58     stream.avail_in = (uInt)sourceLen;\r
59     stream.next_out = dest;\r
60     stream.avail_out = (uInt)destLen;\r
61 \r
62     stream.zalloc = NULL;\r
63     stream.zfree = NULL;\r
64 \r
65     err = inflateInit2(&stream, -15);\r
66     if (err != Z_OK) return err;\r
67 \r
68     err = inflate(&stream, Z_FINISH);\r
69     if (err != Z_STREAM_END) {\r
70         inflateEnd(&stream);\r
71         return err;\r
72     }\r
73     //*destLen = stream.total_out;\r
74 \r
75     return inflateEnd(&stream);\r
76 }\r
77 \r
78 static const char *get_ext(const char *path)\r
79 {\r
80   const char *ext;\r
81   if (strlen(path) < 4)\r
82     return ""; // no ext\r
83 \r
84   // allow 2 or 3 char extensions for now\r
85   ext = path + strlen(path) - 2;\r
86   if (ext[-1] != '.') ext--;\r
87   if (ext[-1] != '.')\r
88     return "";\r
89   return ext;\r
90 }\r
91 \r
92 pm_file *pm_open(const char *path)\r
93 {\r
94   pm_file *file = NULL;\r
95   const char *ext;\r
96   FILE *f;\r
97 \r
98   if (path == NULL)\r
99     return NULL;\r
100 \r
101   ext = get_ext(path);\r
102 #ifndef NO_ZLIB\r
103   if (strcasecmp(ext, "zip") == 0)\r
104   {\r
105     struct zipent *zipentry;\r
106     gzFile gzf = NULL;\r
107     ZIP *zipfile;\r
108     int i;\r
109 \r
110     zipfile = openzip(path);\r
111     if (zipfile != NULL)\r
112     {\r
113       /* search for suitable file (right extension or large enough file) */\r
114       while ((zipentry = readzip(zipfile)) != NULL)\r
115       {\r
116         ext = get_ext(zipentry->name);\r
117 \r
118         if (zipentry->uncompressed_size >= 32*1024)\r
119           goto found_rom_zip;\r
120 \r
121         for (i = 0; i < sizeof(rom_exts)/sizeof(rom_exts[0]); i++)\r
122           if (strcasecmp(ext, rom_exts[i]) == 0)\r
123             goto found_rom_zip;\r
124       }\r
125 \r
126       /* zipfile given, but nothing found suitable for us inside */\r
127       goto zip_failed;\r
128 \r
129 found_rom_zip:\r
130       /* try to convert to gzip stream, so we could use standard gzio functions from zlib */\r
131       gzf = zip2gz(zipfile, zipentry);\r
132       if (gzf == NULL)  goto zip_failed;\r
133 \r
134       file = calloc(1, sizeof(*file));\r
135       if (file == NULL) goto zip_failed;\r
136       file->file  = zipfile;\r
137       file->param = gzf;\r
138       file->size  = zipentry->uncompressed_size;\r
139       file->type  = PMT_ZIP;\r
140       strncpy(file->ext, ext, sizeof(file->ext) - 1);\r
141       return file;\r
142 \r
143 zip_failed:\r
144       if (gzf) {\r
145         gzclose(gzf);\r
146         zipfile->fp = NULL; // gzclose() closed it\r
147       }\r
148       closezip(zipfile);\r
149       return NULL;\r
150     }\r
151   }\r
152   else\r
153 #endif\r
154   if (strcasecmp(ext, "cso") == 0)\r
155   {\r
156     cso_struct *cso = NULL, *tmp = NULL;\r
157     int size;\r
158     f = fopen(path, "rb");\r
159     if (f == NULL)\r
160       goto cso_failed;\r
161 \r
162 #ifdef __GP2X__\r
163     /* we use our own buffering */\r
164     setvbuf(f, NULL, _IONBF, 0);\r
165 #endif\r
166 \r
167     cso = malloc(sizeof(*cso));\r
168     if (cso == NULL)\r
169       goto cso_failed;\r
170 \r
171     if (fread(&cso->header, 1, sizeof(cso->header), f) != sizeof(cso->header))\r
172       goto cso_failed;\r
173 \r
174     if (strncmp(cso->header.magic, "CISO", 4) != 0) {\r
175       elprintf(EL_STATUS, "cso: bad header");\r
176       goto cso_failed;\r
177     }\r
178 \r
179     if (cso->header.block_size != 2048) {\r
180       elprintf(EL_STATUS, "cso: bad block size (%u)", cso->header.block_size);\r
181       goto cso_failed;\r
182     }\r
183 \r
184     size = ((cso->header.total_bytes >> 11) + 1)*4 + sizeof(*cso);\r
185     tmp = realloc(cso, size);\r
186     if (tmp == NULL)\r
187       goto cso_failed;\r
188     cso = tmp;\r
189     elprintf(EL_STATUS, "allocated %i bytes for CSO struct", size);\r
190 \r
191     size -= sizeof(*cso); // index size\r
192     if (fread(cso->index, 1, size, f) != size) {\r
193       elprintf(EL_STATUS, "cso: premature EOF");\r
194       goto cso_failed;\r
195     }\r
196 \r
197     // all ok\r
198     cso->fpos_in = ftell(f);\r
199     cso->fpos_out = 0;\r
200     cso->block_in_buff = -1;\r
201     file = calloc(1, sizeof(*file));\r
202     if (file == NULL) goto cso_failed;\r
203     file->file  = f;\r
204     file->param = cso;\r
205     file->size  = cso->header.total_bytes;\r
206     file->type  = PMT_CSO;\r
207     return file;\r
208 \r
209 cso_failed:\r
210     if (cso != NULL) free(cso);\r
211     if (f != NULL) fclose(f);\r
212     return NULL;\r
213   }\r
214 \r
215   /* not a zip, treat as uncompressed file */\r
216   f = fopen(path, "rb");\r
217   if (f == NULL) return NULL;\r
218 \r
219   file = calloc(1, sizeof(*file));\r
220   if (file == NULL) {\r
221     fclose(f);\r
222     return NULL;\r
223   }\r
224   fseek(f, 0, SEEK_END);\r
225   file->file  = f;\r
226   file->param = NULL;\r
227   file->size  = ftell(f);\r
228   file->type  = PMT_UNCOMPRESSED;\r
229   strncpy(file->ext, ext, sizeof(file->ext) - 1);\r
230   fseek(f, 0, SEEK_SET);\r
231 \r
232 #ifdef __GP2X__\r
233   if (file->size > 0x400000)\r
234     /* we use our own buffering */\r
235     setvbuf(f, NULL, _IONBF, 0);\r
236 #endif\r
237 \r
238   return file;\r
239 }\r
240 \r
241 size_t pm_read(void *ptr, size_t bytes, pm_file *stream)\r
242 {\r
243   int ret;\r
244 \r
245   if (stream->type == PMT_UNCOMPRESSED)\r
246   {\r
247     ret = fread(ptr, 1, bytes, stream->file);\r
248   }\r
249 #ifndef NO_ZLIB\r
250   else if (stream->type == PMT_ZIP)\r
251   {\r
252     gzFile gf = stream->param;\r
253     int err;\r
254     ret = gzread(gf, ptr, bytes);\r
255     err = gzerror2(gf);\r
256     if (ret > 0 && (err == Z_DATA_ERROR || err == Z_STREAM_END))\r
257       /* we must reset stream pointer or else next seek/read fails */\r
258       gzrewind(gf);\r
259   }\r
260 #endif\r
261   else if (stream->type == PMT_CSO)\r
262   {\r
263     cso_struct *cso = stream->param;\r
264     int read_pos, read_len, out_offs, rret;\r
265     int block = cso->fpos_out >> 11;\r
266     int index = cso->index[block];\r
267     int index_end = cso->index[block+1];\r
268     unsigned char *out = ptr, *tmp_dst;\r
269 \r
270     ret = 0;\r
271     while (bytes != 0)\r
272     {\r
273       out_offs = cso->fpos_out&0x7ff;\r
274       if (out_offs == 0 && bytes >= 2048)\r
275            tmp_dst = out;\r
276       else tmp_dst = cso->out_buff;\r
277 \r
278       read_pos = (index&0x7fffffff) << cso->header.align;\r
279 \r
280       if (index < 0) {\r
281         if (read_pos != cso->fpos_in)\r
282           fseek(stream->file, read_pos, SEEK_SET);\r
283         rret = fread(tmp_dst, 1, 2048, stream->file);\r
284         cso->fpos_in = read_pos + rret;\r
285         if (rret != 2048) break;\r
286       } else {\r
287         read_len = (((index_end&0x7fffffff) << cso->header.align) - read_pos) & 0xfff;\r
288         if (block != cso->block_in_buff)\r
289         {\r
290           if (read_pos != cso->fpos_in)\r
291             fseek(stream->file, read_pos, SEEK_SET);\r
292           rret = fread(cso->in_buff, 1, read_len, stream->file);\r
293           cso->fpos_in = read_pos + rret;\r
294           if (rret != read_len) {\r
295             elprintf(EL_STATUS, "cso: read failed @ %08x", read_pos);\r
296             break;\r
297           }\r
298           cso->block_in_buff = block;\r
299         }\r
300         rret = uncompress_buf(tmp_dst, 2048, cso->in_buff, read_len);\r
301         if (rret != 0) {\r
302           elprintf(EL_STATUS, "cso: uncompress failed @ %08x with %i", read_pos, rret);\r
303           break;\r
304         }\r
305       }\r
306 \r
307       rret = 2048;\r
308       if (out_offs != 0 || bytes < 2048) {\r
309         //elprintf(EL_STATUS, "cso: unaligned/nonfull @ %08x, offs=%i, len=%u", cso->fpos_out, out_offs, bytes);\r
310         if (bytes < rret) rret = bytes;\r
311         if (2048 - out_offs < rret) rret = 2048 - out_offs;\r
312         memcpy(out, tmp_dst + out_offs, rret);\r
313       }\r
314       ret += rret;\r
315       out += rret;\r
316       cso->fpos_out += rret;\r
317       bytes -= rret;\r
318       block++;\r
319       index = index_end;\r
320       index_end = cso->index[block+1];\r
321     }\r
322   }\r
323   else\r
324     ret = 0;\r
325 \r
326   return ret;\r
327 }\r
328 \r
329 int pm_seek(pm_file *stream, long offset, int whence)\r
330 {\r
331   if (stream->type == PMT_UNCOMPRESSED)\r
332   {\r
333     fseek(stream->file, offset, whence);\r
334     return ftell(stream->file);\r
335   }\r
336 #ifndef NO_ZLIB\r
337   else if (stream->type == PMT_ZIP)\r
338   {\r
339     if (PicoMessage != NULL && offset > 6*1024*1024) {\r
340       long pos = gztell((gzFile) stream->param);\r
341       if (offset < pos || offset - pos > 6*1024*1024)\r
342         PicoMessage("Decompressing data...");\r
343     }\r
344     return gzseek((gzFile) stream->param, offset, whence);\r
345   }\r
346 #endif\r
347   else if (stream->type == PMT_CSO)\r
348   {\r
349     cso_struct *cso = stream->param;\r
350     switch (whence)\r
351     {\r
352       case SEEK_CUR: cso->fpos_out += offset; break;\r
353       case SEEK_SET: cso->fpos_out  = offset; break;\r
354       case SEEK_END: cso->fpos_out  = cso->header.total_bytes - offset; break;\r
355     }\r
356     return cso->fpos_out;\r
357   }\r
358   else\r
359     return -1;\r
360 }\r
361 \r
362 int pm_close(pm_file *fp)\r
363 {\r
364   int ret = 0;\r
365 \r
366   if (fp == NULL) return EOF;\r
367 \r
368   if (fp->type == PMT_UNCOMPRESSED)\r
369   {\r
370     fclose(fp->file);\r
371   }\r
372 #ifndef NO_ZLIB\r
373   else if (fp->type == PMT_ZIP)\r
374   {\r
375     ZIP *zipfile = fp->file;\r
376     gzclose((gzFile) fp->param);\r
377     zipfile->fp = NULL; // gzclose() closed it\r
378     closezip(zipfile);\r
379   }\r
380 #endif\r
381   else if (fp->type == PMT_CSO)\r
382   {\r
383     free(fp->param);\r
384     fclose(fp->file);\r
385   }\r
386   else\r
387     ret = EOF;\r
388 \r
389   free(fp);\r
390   return ret;\r
391 }\r
392 \r
393 // byteswap, data needs to be int aligned, src can match dst\r
394 void Byteswap(void *dst, const void *src, int len)\r
395 {\r
396   const unsigned int *ps = src;\r
397   unsigned int *pd = dst;\r
398   int i, m;\r
399 \r
400   if (len < 2)\r
401     return;\r
402 \r
403   m = 0x00ff00ff;\r
404   for (i = 0; i < len / 4; i++) {\r
405     unsigned int t = ps[i];\r
406     pd[i] = ((t & m) << 8) | ((t & ~m) >> 8);\r
407   }\r
408 }\r
409 \r
410 // Interleve a 16k block and byteswap\r
411 static int InterleveBlock(unsigned char *dest,unsigned char *src)\r
412 {\r
413   int i=0;\r
414   for (i=0;i<0x2000;i++) dest[(i<<1)  ]=src[       i]; // Odd\r
415   for (i=0;i<0x2000;i++) dest[(i<<1)+1]=src[0x2000+i]; // Even\r
416   return 0;\r
417 }\r
418 \r
419 // Decode a SMD file\r
420 static int DecodeSmd(unsigned char *data,int len)\r
421 {\r
422   unsigned char *temp=NULL;\r
423   int i=0;\r
424 \r
425   temp=(unsigned char *)malloc(0x4000);\r
426   if (temp==NULL) return 1;\r
427   memset(temp,0,0x4000);\r
428 \r
429   // Interleve each 16k block and shift down by 0x200:\r
430   for (i=0; i+0x4200<=len; i+=0x4000)\r
431   {\r
432     InterleveBlock(temp,data+0x200+i); // Interleve 16k to temporary buffer\r
433     memcpy(data+i,temp,0x4000); // Copy back in\r
434   }\r
435 \r
436   free(temp);\r
437   return 0;\r
438 }\r
439 \r
440 static unsigned char *PicoCartAlloc(int filesize, int is_sms)\r
441 {\r
442   unsigned char *rom;\r
443 \r
444   if (is_sms) {\r
445     // make size power of 2 for easier banking handling\r
446     int s = 0, tmp = filesize;\r
447     while ((tmp >>= 1) != 0)\r
448       s++;\r
449     if (filesize > (1 << s))\r
450       s++;\r
451     rom_alloc_size = 1 << s;\r
452     // be sure we can cover all address space\r
453     if (rom_alloc_size < 0x10000)\r
454       rom_alloc_size = 0x10000;\r
455   }\r
456   else {\r
457     // make alloc size at least sizeof(mcd_state),\r
458     // in case we want to switch to CD mode\r
459     if (filesize < sizeof(mcd_state))\r
460       filesize = sizeof(mcd_state);\r
461 \r
462     // align to 512K for memhandlers\r
463     rom_alloc_size = (filesize + 0x7ffff) & ~0x7ffff;\r
464   }\r
465 \r
466   if (rom_alloc_size - filesize < 4)\r
467     rom_alloc_size += 4; // padding for out-of-bound exec protection\r
468 \r
469   // Allocate space for the rom plus padding\r
470   // use special address for 32x dynarec\r
471   rom = plat_mmap(0x02000000, rom_alloc_size, 0, 0);\r
472   return rom;\r
473 }\r
474 \r
475 int PicoCartLoad(pm_file *f,unsigned char **prom,unsigned int *psize,int is_sms)\r
476 {\r
477   unsigned char *rom;\r
478   int size, bytes_read;\r
479 \r
480   if (f == NULL)\r
481     return 1;\r
482 \r
483   size = f->size;\r
484   if (size <= 0) return 1;\r
485   size = (size+3)&~3; // Round up to a multiple of 4\r
486 \r
487   // Allocate space for the rom plus padding\r
488   rom = PicoCartAlloc(size, is_sms);\r
489   if (rom == NULL) {\r
490     elprintf(EL_STATUS, "out of memory (wanted %i)", size);\r
491     return 2;\r
492   }\r
493 \r
494   if (PicoCartLoadProgressCB != NULL)\r
495   {\r
496     // read ROM in blocks, just for fun\r
497     int ret;\r
498     unsigned char *p = rom;\r
499     bytes_read=0;\r
500     do\r
501     {\r
502       int todo = size - bytes_read;\r
503       if (todo > 256*1024) todo = 256*1024;\r
504       ret = pm_read(p,todo,f);\r
505       bytes_read += ret;\r
506       p += ret;\r
507       PicoCartLoadProgressCB(bytes_read * 100 / size);\r
508     }\r
509     while (ret > 0);\r
510   }\r
511   else\r
512     bytes_read = pm_read(rom,size,f); // Load up the rom\r
513   if (bytes_read <= 0) {\r
514     elprintf(EL_STATUS, "read failed");\r
515     plat_munmap(rom, rom_alloc_size);\r
516     return 3;\r
517   }\r
518 \r
519   if (!is_sms)\r
520   {\r
521     // maybe we are loading MegaCD BIOS?\r
522     if (!(PicoAHW & PAHW_MCD) && size == 0x20000 && (!strncmp((char *)rom+0x124, "BOOT", 4) ||\r
523          !strncmp((char *)rom+0x128, "BOOT", 4))) {\r
524       PicoAHW |= PAHW_MCD;\r
525     }\r
526 \r
527     // Check for SMD:\r
528     if (size >= 0x4200 && (size&0x3fff) == 0x200 &&\r
529         ((rom[0x2280] == 'S' && rom[0x280] == 'E') || (rom[0x280] == 'S' && rom[0x2281] == 'E'))) {\r
530       elprintf(EL_STATUS, "SMD format detected.");\r
531       DecodeSmd(rom,size); size-=0x200; // Decode and byteswap SMD\r
532     }\r
533     else Byteswap(rom, rom, size); // Just byteswap\r
534   }\r
535   else\r
536   {\r
537     if (size >= 0x4200 && (size&0x3fff) == 0x200) {\r
538       elprintf(EL_STATUS, "SMD format detected.");\r
539       // at least here it's not interleaved\r
540       size -= 0x200;\r
541       memmove(rom, rom + 0x200, size);\r
542     }\r
543   }\r
544 \r
545   if (prom)  *prom = rom;\r
546   if (psize) *psize = size;\r
547 \r
548   return 0;\r
549 }\r
550 \r
551 // Insert a cartridge:\r
552 int PicoCartInsert(unsigned char *rom, unsigned int romsize, const char *carthw_cfg)\r
553 {\r
554   // notaz: add a 68k "jump one op back" opcode to the end of ROM.\r
555   // This will hang the emu, but will prevent nasty crashes.\r
556   // note: 4 bytes are padded to every ROM\r
557   if (rom != NULL)\r
558     *(unsigned long *)(rom+romsize) = 0xFFFE4EFA; // 4EFA FFFE byteswapped\r
559 \r
560   Pico.rom=rom;\r
561   Pico.romsize=romsize;\r
562 \r
563   if (SRam.data) {\r
564     free(SRam.data);\r
565     SRam.data = NULL;\r
566   }\r
567 \r
568   if (PicoCartUnloadHook != NULL) {\r
569     PicoCartUnloadHook();\r
570     PicoCartUnloadHook = NULL;\r
571   }\r
572   pdb_cleanup();\r
573 \r
574   PicoAHW &= PAHW_MCD|PAHW_SMS;\r
575 \r
576   PicoCartMemSetup = NULL;\r
577   PicoDmaHook = NULL;\r
578   PicoResetHook = NULL;\r
579   PicoLineHook = NULL;\r
580   PicoLoadStateHook = NULL;\r
581   carthw_chunks = NULL;\r
582 \r
583   if (!(PicoAHW & (PAHW_MCD|PAHW_SMS)))\r
584     PicoCartDetect(carthw_cfg);\r
585 \r
586   // setup correct memory map for loaded ROM\r
587   switch (PicoAHW) {\r
588     default:\r
589       elprintf(EL_STATUS|EL_ANOMALY, "starting in unknown hw configuration: %x", PicoAHW);\r
590     case 0:\r
591     case PAHW_SVP:  PicoMemSetup(); break;\r
592     case PAHW_MCD:  PicoMemSetupCD(); break;\r
593     case PAHW_PICO: PicoMemSetupPico(); break;\r
594     case PAHW_SMS:  PicoMemSetupMS(); break;\r
595   }\r
596 \r
597   if (PicoCartMemSetup != NULL)\r
598     PicoCartMemSetup();\r
599 \r
600   if (PicoAHW & PAHW_SMS)\r
601     PicoPowerMS();\r
602   else\r
603     PicoPower();\r
604 \r
605   PicoGameLoaded = 1;\r
606   return 0;\r
607 }\r
608 \r
609 int PicoCartResize(int newsize)\r
610 {\r
611   void *tmp = plat_mremap(Pico.rom, rom_alloc_size, newsize);\r
612   if (tmp == NULL)\r
613     return -1;\r
614 \r
615   Pico.rom = tmp;\r
616   rom_alloc_size = newsize;\r
617   return 0;\r
618 }\r
619 \r
620 void PicoCartUnload(void)\r
621 {\r
622   if (PicoCartUnloadHook != NULL) {\r
623     PicoCartUnloadHook();\r
624     PicoCartUnloadHook = NULL;\r
625   }\r
626 \r
627   if (PicoAHW & PAHW_32X)\r
628     PicoUnload32x();\r
629 \r
630   if (Pico.rom != NULL) {\r
631     SekFinishIdleDet();\r
632     plat_munmap(Pico.rom, rom_alloc_size);\r
633     Pico.rom = NULL;\r
634   }\r
635   PicoGameLoaded = 0;\r
636 }\r
637 \r
638 static unsigned int rom_crc32(void)\r
639 {\r
640   unsigned int crc;\r
641   elprintf(EL_STATUS, "caclulating CRC32..");\r
642 \r
643   // have to unbyteswap for calculation..\r
644   Byteswap(Pico.rom, Pico.rom, Pico.romsize);\r
645   crc = crc32(0, Pico.rom, Pico.romsize);\r
646   Byteswap(Pico.rom, Pico.rom, Pico.romsize);\r
647   return crc;\r
648 }\r
649 \r
650 static int rom_strcmp(int rom_offset, const char *s1)\r
651 {\r
652   int i, len = strlen(s1);\r
653   const char *s_rom = (const char *)Pico.rom;\r
654   if (rom_offset + len > Pico.romsize)\r
655     return 0;\r
656   for (i = 0; i < len; i++)\r
657     if (s1[i] != s_rom[(i + rom_offset) ^ 1])\r
658       return 1;\r
659   return 0;\r
660 }\r
661 \r
662 static unsigned int rom_read32(int addr)\r
663 {\r
664   unsigned short *m = (unsigned short *)(Pico.rom + addr);\r
665   return (m[0] << 16) | m[1];\r
666 }\r
667 \r
668 static char *sskip(char *s)\r
669 {\r
670   while (*s && isspace_(*s))\r
671     s++;\r
672   return s;\r
673 }\r
674 \r
675 static void rstrip(char *s)\r
676 {\r
677   char *p;\r
678   for (p = s + strlen(s) - 1; p >= s; p--)\r
679     if (isspace_(*p))\r
680       *p = 0;\r
681 }\r
682 \r
683 static int parse_3_vals(char *p, int *val0, int *val1, int *val2)\r
684 {\r
685   char *r;\r
686   *val0 = strtoul(p, &r, 0);\r
687   if (r == p)\r
688     goto bad;\r
689   p = sskip(r);\r
690   if (*p++ != ',')\r
691     goto bad;\r
692   *val1 = strtoul(p, &r, 0);\r
693   if (r == p)\r
694     goto bad;\r
695   p = sskip(r);\r
696   if (*p++ != ',')\r
697     goto bad;\r
698   *val2 = strtoul(p, &r, 0);\r
699   if (r == p)\r
700     goto bad;\r
701 \r
702   return 1;\r
703 bad:\r
704   return 0;\r
705 }\r
706 \r
707 static int is_expr(const char *expr, char **pr)\r
708 {\r
709   int len = strlen(expr);\r
710   char *p = *pr;\r
711 \r
712   if (strncmp(expr, p, len) != 0)\r
713     return 0;\r
714   p = sskip(p + len);\r
715   if (*p != '=')\r
716     return 0; // wrong or malformed\r
717 \r
718   *pr = sskip(p + 1);\r
719   return 1;\r
720 }\r
721 \r
722 #include "carthw_cfg.c"\r
723 \r
724 static void parse_carthw(const char *carthw_cfg, int *fill_sram)\r
725 {\r
726   int line = 0, any_checks_passed = 0, skip_sect = 0;\r
727   const char *s, *builtin = builtin_carthw_cfg;\r
728   int tmp, rom_crc = 0;\r
729   char buff[256], *p, *r;\r
730   FILE *f;\r
731 \r
732   f = fopen(carthw_cfg, "r");\r
733   if (f == NULL)\r
734     f = fopen("pico/carthw.cfg", "r");\r
735   if (f == NULL)\r
736     elprintf(EL_STATUS, "couldn't open carthw.cfg!");\r
737 \r
738   for (;;)\r
739   {\r
740     if (f != NULL) {\r
741       p = fgets(buff, sizeof(buff), f);\r
742       if (p == NULL)\r
743         break;\r
744     }\r
745     else {\r
746       if (*builtin == 0)\r
747         break;\r
748       for (s = builtin; *s != 0 && *s != '\n'; s++)\r
749         ;\r
750       while (*s == '\n')\r
751         s++;\r
752       tmp = s - builtin;\r
753       if (tmp > sizeof(buff) - 1)\r
754         tmp = sizeof(buff) - 1;\r
755       memcpy(buff, builtin, tmp);\r
756       buff[tmp] = 0;\r
757       p = buff;\r
758       builtin = s;\r
759     }\r
760 \r
761     line++;\r
762     p = sskip(p);\r
763     if (*p == 0 || *p == '#')\r
764       continue;\r
765 \r
766     if (*p == '[') {\r
767       any_checks_passed = 0;\r
768       skip_sect = 0;\r
769       continue;\r
770     }\r
771     \r
772     if (skip_sect)\r
773       continue;\r
774 \r
775     /* look for checks */\r
776     if (is_expr("check_str", &p))\r
777     {\r
778       int offs;\r
779       offs = strtoul(p, &r, 0);\r
780       if (offs < 0 || offs > Pico.romsize) {\r
781         elprintf(EL_STATUS, "carthw:%d: check_str offs out of range: %d\n", line, offs);\r
782         goto bad;\r
783       }\r
784       p = sskip(r);\r
785       if (*p != ',')\r
786         goto bad;\r
787       p = sskip(p + 1);\r
788       if (*p != '"')\r
789         goto bad;\r
790       p++;\r
791       r = strchr(p, '"');\r
792       if (r == NULL)\r
793         goto bad;\r
794       *r = 0;\r
795 \r
796       if (rom_strcmp(offs, p) == 0)\r
797         any_checks_passed = 1;\r
798       else\r
799         skip_sect = 1;\r
800       continue;\r
801     }\r
802     else if (is_expr("check_size_gt", &p))\r
803     {\r
804       int size;\r
805       size = strtoul(p, &r, 0);\r
806       if (r == p || size < 0)\r
807         goto bad;\r
808 \r
809       if (Pico.romsize > size)\r
810         any_checks_passed = 1;\r
811       else\r
812         skip_sect = 1;\r
813       continue;\r
814     }\r
815     else if (is_expr("check_csum", &p))\r
816     {\r
817       int csum;\r
818       csum = strtoul(p, &r, 0);\r
819       if (r == p || (csum & 0xffff0000))\r
820         goto bad;\r
821 \r
822       if (csum == (rom_read32(0x18c) & 0xffff))\r
823         any_checks_passed = 1;\r
824       else\r
825         skip_sect = 1;\r
826       continue;\r
827     }\r
828     else if (is_expr("check_crc32", &p))\r
829     {\r
830       unsigned int crc;\r
831       crc = strtoul(p, &r, 0);\r
832       if (r == p)\r
833         goto bad;\r
834 \r
835       if (rom_crc == 0)\r
836         rom_crc = rom_crc32();\r
837       if (crc == rom_crc)\r
838         any_checks_passed = 1;\r
839       else\r
840         skip_sect = 1;\r
841       continue;\r
842     }\r
843 \r
844     /* now time for actions */\r
845     if (is_expr("hw", &p)) {\r
846       if (!any_checks_passed)\r
847         goto no_checks;\r
848       rstrip(p);\r
849 \r
850       if      (strcmp(p, "svp") == 0)\r
851         PicoSVPStartup();\r
852       else if (strcmp(p, "pico") == 0)\r
853         PicoInitPico();\r
854       else if (strcmp(p, "prot") == 0)\r
855         carthw_sprot_startup();\r
856       else if (strcmp(p, "ssf2_mapper") == 0)\r
857         carthw_ssf2_startup();\r
858       else if (strcmp(p, "x_in_1_mapper") == 0)\r
859         carthw_Xin1_startup();\r
860       else if (strcmp(p, "realtec_mapper") == 0)\r
861         carthw_realtec_startup();\r
862       else if (strcmp(p, "radica_mapper") == 0)\r
863         carthw_radica_startup();\r
864       else if (strcmp(p, "piersolar_mapper") == 0)\r
865         carthw_pier_startup();\r
866       else if (strcmp(p, "prot_lk3") == 0)\r
867         carthw_prot_lk3_startup();\r
868       else {\r
869         elprintf(EL_STATUS, "carthw:%d: unsupported mapper: %s", line, p);\r
870         skip_sect = 1;\r
871       }\r
872       continue;\r
873     }\r
874     if (is_expr("sram_range", &p)) {\r
875       int start, end;\r
876 \r
877       if (!any_checks_passed)\r
878         goto no_checks;\r
879       rstrip(p);\r
880 \r
881       start = strtoul(p, &r, 0);\r
882       if (r == p)\r
883         goto bad;\r
884       p = sskip(r);\r
885       if (*p != ',')\r
886         goto bad;\r
887       p = sskip(p + 1);\r
888       end = strtoul(p, &r, 0);\r
889       if (r == p)\r
890         goto bad;\r
891       if (((start | end) & 0xff000000) || start > end) {\r
892         elprintf(EL_STATUS, "carthw:%d: bad sram_range: %08x - %08x", line, start, end);\r
893         goto bad_nomsg;\r
894       }\r
895       SRam.start = start;\r
896       SRam.end = end;\r
897       continue;\r
898     }\r
899     else if (is_expr("prop", &p)) {\r
900       if (!any_checks_passed)\r
901         goto no_checks;\r
902       rstrip(p);\r
903 \r
904       if      (strcmp(p, "no_sram") == 0)\r
905         SRam.flags &= ~SRF_ENABLED;\r
906       else if (strcmp(p, "no_eeprom") == 0)\r
907         SRam.flags &= ~SRF_EEPROM;\r
908       else if (strcmp(p, "filled_sram") == 0)\r
909         *fill_sram = 1;\r
910       else if (strcmp(p, "force_6btn") == 0)\r
911         PicoQuirks |= PQUIRK_FORCE_6BTN;\r
912       else {\r
913         elprintf(EL_STATUS, "carthw:%d: unsupported prop: %s", line, p);\r
914         goto bad_nomsg;\r
915       }\r
916       elprintf(EL_STATUS, "game prop: %s", p);\r
917       continue;\r
918     }\r
919     else if (is_expr("eeprom_type", &p)) {\r
920       int type;\r
921       if (!any_checks_passed)\r
922         goto no_checks;\r
923       rstrip(p);\r
924 \r
925       type = strtoul(p, &r, 0);\r
926       if (r == p || type < 0)\r
927         goto bad;\r
928       SRam.eeprom_type = type;\r
929       SRam.flags |= SRF_EEPROM;\r
930       continue;\r
931     }\r
932     else if (is_expr("eeprom_lines", &p)) {\r
933       int scl, sda_in, sda_out;\r
934       if (!any_checks_passed)\r
935         goto no_checks;\r
936       rstrip(p);\r
937 \r
938       if (!parse_3_vals(p, &scl, &sda_in, &sda_out))\r
939         goto bad;\r
940       if (scl < 0 || scl > 15 || sda_in < 0 || sda_in > 15 ||\r
941           sda_out < 0 || sda_out > 15)\r
942         goto bad;\r
943 \r
944       SRam.eeprom_bit_cl = scl;\r
945       SRam.eeprom_bit_in = sda_in;\r
946       SRam.eeprom_bit_out= sda_out;\r
947       continue;\r
948     }\r
949     else if ((tmp = is_expr("prot_ro_value16", &p)) || is_expr("prot_rw_value16", &p)) {\r
950       int addr, mask, val;\r
951       if (!any_checks_passed)\r
952         goto no_checks;\r
953       rstrip(p);\r
954 \r
955       if (!parse_3_vals(p, &addr, &mask, &val))\r
956         goto bad;\r
957 \r
958       carthw_sprot_new_location(addr, mask, val, tmp ? 1 : 0);\r
959       continue;\r
960     }\r
961 \r
962 \r
963 bad:\r
964     elprintf(EL_STATUS, "carthw:%d: unrecognized expression: %s", line, buff);\r
965 bad_nomsg:\r
966     skip_sect = 1;\r
967     continue;\r
968 \r
969 no_checks:\r
970     elprintf(EL_STATUS, "carthw:%d: command without any checks before it: %s", line, buff);\r
971     skip_sect = 1;\r
972     continue;\r
973   }\r
974 \r
975   if (f != NULL)\r
976     fclose(f);\r
977 }\r
978 \r
979 /*\r
980  * various cart-specific things, which can't be handled by generic code\r
981  */\r
982 static void PicoCartDetect(const char *carthw_cfg)\r
983 {\r
984   int fill_sram = 0;\r
985 \r
986   memset(&SRam, 0, sizeof(SRam));\r
987   if (Pico.rom[0x1B1] == 'R' && Pico.rom[0x1B0] == 'A')\r
988   {\r
989     SRam.start =  rom_read32(0x1B4) & ~0xff000001; // align\r
990     SRam.end   = (rom_read32(0x1B8) & ~0xff000000) | 1;\r
991     if (Pico.rom[0x1B2] & 0x40)\r
992       // EEPROM\r
993       SRam.flags |= SRF_EEPROM;\r
994     SRam.flags |= SRF_ENABLED;\r
995   }\r
996   if (SRam.end == 0 || SRam.start > SRam.end)\r
997   {\r
998     // some games may have bad headers, like S&K and Sonic3\r
999     // note: majority games use 0x200000 as starting address, but there are some which\r
1000     // use something else (0x300000 by HardBall '95). Luckily they have good headers.\r
1001     SRam.start = 0x200000;\r
1002     SRam.end   = 0x203FFF;\r
1003     SRam.flags |= SRF_ENABLED;\r
1004   }\r
1005 \r
1006   // set EEPROM defaults, in case it gets detected\r
1007   SRam.eeprom_type   = 0; // 7bit (24C01)\r
1008   SRam.eeprom_bit_cl = 1;\r
1009   SRam.eeprom_bit_in = 0;\r
1010   SRam.eeprom_bit_out= 0;\r
1011 \r
1012   if (carthw_cfg != NULL)\r
1013     parse_carthw(carthw_cfg, &fill_sram);\r
1014 \r
1015   if (SRam.flags & SRF_ENABLED)\r
1016   {\r
1017     if (SRam.flags & SRF_EEPROM)\r
1018       SRam.size = 0x2000;\r
1019     else\r
1020       SRam.size = SRam.end - SRam.start + 1;\r
1021 \r
1022     SRam.data = calloc(SRam.size, 1);\r
1023     if (SRam.data == NULL)\r
1024       SRam.flags &= ~SRF_ENABLED;\r
1025 \r
1026     if (SRam.eeprom_type == 1)  // 1 == 0 in PD EEPROM code\r
1027       SRam.eeprom_type = 0;\r
1028   }\r
1029 \r
1030   if ((SRam.flags & SRF_ENABLED) && fill_sram)\r
1031   {\r
1032     elprintf(EL_STATUS, "SRAM fill");\r
1033     memset(SRam.data, 0xff, SRam.size);\r
1034   }\r
1035 \r
1036   // Unusual region 'code'\r
1037   if (rom_strcmp(0x1f0, "EUROPE") == 0 || rom_strcmp(0x1f0, "Europe") == 0)\r
1038     *(int *) (Pico.rom + 0x1f0) = 0x20204520;\r
1039 }\r
1040 \r
1041 // vim:shiftwidth=2:expandtab\r