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