]> Shamusworld >> Repos - virtualjaguar/blob - src/file.cpp
Added more developer friendly stuff to Alpine mode.
[virtualjaguar] / src / file.cpp
1 //
2 // FILE.CPP
3 //
4 // File support
5 // by James L. Hammons
6 // (C) 2010 Underground Software
7 //
8 // JLH = James L. Hammons <jlhamm@acm.org>
9 //
10 // Who  When        What
11 // ---  ----------  -------------------------------------------------------------
12 // JLH  01/16/2010  Created this log ;-)
13 // JLH  02/28/2010  Added functions to look inside .ZIP files and handle contents
14 //
15
16 #include "file.h"
17
18 #include <stdarg.h>
19 #include <string.h>
20 #include "crc32.h"
21 #include "eeprom.h"
22 #include "jaguar.h"
23 #include "log.h"
24 #include "memory.h"
25 #include "universalhdr.h"
26 #include "unzip.h"
27 #include "zlib.h"
28
29 // Private function prototypes
30
31 static int gzfilelength(gzFile gd);
32 static bool CheckExtension(const char * filename, const char * ext);
33 //static int ParseFileType(uint8 header1, uint8 header2, uint32 size);
34
35 // Private variables/enums
36
37
38 //
39 // Generic ROM loading
40 //
41 uint32 JaguarLoadROM(uint8 * &rom, char * path)
42 {
43 // We really should have some kind of sanity checking for the ROM size here to prevent
44 // a buffer overflow... !!! FIX !!!
45 #warning "!!! FIX !!! Should have sanity checking for ROM size to prevent buffer overflow!"
46         uint32 romSize = 0;
47
48         WriteLog("JaguarLoadROM: Attempting to load file '%s'...", path);
49         char * ext = strrchr(path, '.');
50
51         // No filename extension == YUO FAIL IT (it is loading the file).
52         // This is naive, but it works. But should probably come up with something a little
53         // more robust, to prevent problems with dopes trying to exploit this.
54         if (ext == NULL)
55         {
56                 WriteLog("FAILED!\n");
57                 return 0;
58         }
59
60         WriteLog("Succeeded in finding extension (%s)!\n", ext);
61         WriteLog("VJ: Loading \"%s\"...", path);
62
63         if (strcasecmp(ext, ".zip") == 0)
64         {
65                 // Handle ZIP file loading here...
66                 WriteLog("(ZIPped)...");
67
68 //              uint8_t * buffer = NULL;
69 //              romSize = GetFileFromZIP(path, FT_SOFTWARE, buffer);
70                 romSize = GetFileFromZIP(path, FT_SOFTWARE, rom);
71
72                 if (romSize == 0)
73                 {
74                         WriteLog("Failed!\n");
75                         return 0;
76                 }
77
78 //              memcpy(rom, buffer, romSize);
79 //              delete[] buffer;
80         }
81         else
82         {
83                 // Handle gzipped files transparently [Adam Green]...
84
85                 gzFile fp = gzopen(path, "rb");
86
87                 if (fp == NULL)
88                 {
89                         WriteLog("Failed!\n");
90                         return 0;
91                 }
92
93                 romSize = gzfilelength(fp);
94                 rom = new uint8[romSize];
95                 gzseek(fp, 0, SEEK_SET);
96                 gzread(fp, rom, romSize);
97                 gzclose(fp);
98         }
99
100         WriteLog("OK (%i bytes)\n", romSize);
101
102         return romSize;
103 }
104
105 //
106 // Jaguar file loading
107 // We do a more intelligent file analysis here instead of relying on (possible false)
108 // file extensions which people don't seem to give two shits about anyway. :-(
109 //
110 bool JaguarLoadFile(char * path)
111 {
112         uint8 * buffer = NULL;
113         jaguarROMSize = JaguarLoadROM(buffer, path);
114
115         if (jaguarROMSize == 0)
116         {
117                 // It's up to the GUI to report errors, not us. :-)
118                 WriteLog("FILE: Could not load ROM from file \"%s\"...\nAborting load!\n", path);
119                 return false;
120         }
121
122         jaguarMainROMCRC32 = crc32_calcCheckSum(buffer, jaguarROMSize);
123         WriteLog("CRC: %08X\n", (unsigned int)jaguarMainROMCRC32);
124 // TODO: Check for EEPROM file in ZIP file. If there is no EEPROM in the user's EEPROM
125 //       directory, copy the one from the ZIP file, if it exists.
126         EepromInit();
127         jaguarRunAddress = 0x802000;                                    // For non-BIOS runs, this is true
128         int fileType = ParseFileType(buffer[0], buffer[1], jaguarROMSize);
129
130         if (fileType == JST_ROM)
131         {
132                 memcpy(jagMemSpace + 0x800000, buffer, jaguarROMSize);
133                 delete[] buffer;
134                 return true;
135         }
136         else if (fileType == JST_ALPINE)
137         {
138                 // File extension ".ROM": Alpine image that loads/runs at $802000
139                 WriteLog("FILE: Setting up Alpine ROM... Run address: 00802000, length: %08X\n", jaguarROMSize);
140                 memset(jagMemSpace + 0x800000, 0xFF, 0x2000);
141                 memcpy(jagMemSpace + 0x802000, buffer, jaguarROMSize);
142                 delete[] buffer;
143
144 // Maybe instead of this, we could try requiring the STUBULATOR ROM? Just a thought...
145                 // Try setting the vector to say, $1000 and putting an instruction there that loops forever:
146                 // This kludge works! Yeah!
147                 SET32(jaguarMainRAM, 0x10, 0x00001000);
148                 SET16(jaguarMainRAM, 0x1000, 0x60FE);           // Here: bra Here
149                 return true;
150         }
151         else if (fileType == JST_ABS_TYPE1)
152         {
153                 // For ABS type 1, run address == load address
154                 uint32 loadAddress = GET32(buffer, 0x16),
155                         codeSize = GET32(buffer, 0x02) + GET32(buffer, 0x06);
156                 WriteLog("FILE: Setting up homebrew (ABS-1)... Run address: %08X, length: %08X\n", loadAddress, codeSize);
157                 memcpy(jagMemSpace + loadAddress, buffer + 0x24, codeSize);
158                 delete[] buffer;
159                 jaguarRunAddress = loadAddress;
160                 return true;
161         }
162         else if (fileType == JST_ABS_TYPE2)
163         {
164                 uint32 loadAddress = GET32(buffer, 0x28), runAddress = GET32(buffer, 0x24),
165                         codeSize = GET32(buffer, 0x18) + GET32(buffer, 0x1C);
166                 WriteLog("FILE: Setting up homebrew (ABS-2)... Run address: %08X, length: %08X\n", runAddress, codeSize);
167                 memcpy(jagMemSpace + loadAddress, buffer + 0xA8, codeSize);
168                 delete[] buffer;
169                 jaguarRunAddress = runAddress;
170                 return true;
171         }
172         else if (fileType == JST_JAGSERVER)
173         {
174                 uint32 loadAddress = GET32(buffer, 0x22), runAddress = GET32(buffer, 0x2A);
175                 WriteLog("FILE: Setting up homebrew (Jag Server)... Run address: %08X, length: %08X\n", runAddress, jaguarROMSize - 0x2E);
176                 memcpy(jagMemSpace + loadAddress, buffer + 0x2E, jaguarROMSize - 0x2E);
177                 delete[] buffer;
178                 jaguarRunAddress = runAddress;
179                 return true;
180         }
181
182         // We can assume we have JST_NONE at this point. :-P
183         return false;
184 }
185
186 //
187 // "Alpine" file loading
188 // Since the developers were coming after us with torches and pitchforks, we decided to
189 // allow this kind of thing. ;-) But ONLY FOR THE DEVS, DAMMIT! O_O
190 //
191 bool AlpineLoadFile(char * path)
192 {
193         uint8 * buffer = NULL;
194         jaguarROMSize = JaguarLoadROM(buffer, path);
195
196         if (jaguarROMSize == 0)
197         {
198                 // It's up to the GUI to deal with failure, not us. ;-)
199                 WriteLog("FILE: Could not load Alpine from file \"%s\"...\nAborting load!\n", path);
200                 return false;
201         }
202
203         jaguarMainROMCRC32 = crc32_calcCheckSum(buffer, jaguarROMSize);
204         WriteLog("CRC: %08X\n", (unsigned int)jaguarMainROMCRC32);
205         EepromInit();
206
207         jaguarRunAddress = 0x802000;
208
209         WriteLog("FILE: Setting up Alpine ROM with non-standard length... Run address: 00802000, length: %08X\n", jaguarROMSize);
210
211         memset(jagMemSpace + 0x800000, 0xFF, 0x2000);
212         memcpy(jagMemSpace + 0x802000, buffer, jaguarROMSize);
213         delete[] buffer;
214
215 // Maybe instead of this, we could try requiring the STUBULATOR ROM? Just a thought...
216         // Try setting the vector to say, $1000 and putting an instruction there that loops forever:
217         // This kludge works! Yeah!
218         SET32(jaguarMainRAM, 0x10, 0x00001000);
219         SET16(jaguarMainRAM, 0x1000, 0x60FE);           // Here: bra Here
220
221         return true;
222 }
223
224 //
225 // Get the length of a (possibly) gzipped file
226 //
227 static int gzfilelength(gzFile gd)
228 {
229    int size = 0, length = 0;
230    unsigned char buffer[0x10000];
231
232    gzrewind(gd);
233
234    do
235    {
236       // Read in chunks until EOF
237       size = gzread(gd, buffer, 0x10000);
238
239       if (size <= 0)
240         break;
241
242       length += size;
243    }
244    while (!gzeof(gd));
245
246    gzrewind(gd);
247    return length;
248 }
249
250 //
251 // Compare extension to passed in filename. If equal, return true; otherwise false.
252 //
253 static bool CheckExtension(const char * filename, const char * ext)
254 {
255         const char * filenameExt = strrchr(filename, '.');      // Get the file's extension (if any)
256         return (strcasecmp(filenameExt, ext) == 0 ? true : false);
257 }
258
259 //
260 // Get file from .ZIP
261 // Returns the size of the file inside the .ZIP file that we're looking at
262 // NOTE: If the thing we're looking for is found, it allocates it in the passed in buffer.
263 //       Which means we have to deallocate it later.
264 //
265 uint32 GetFileFromZIP(const char * zipFile, FileType type, uint8 * &buffer)
266 {
267 // NOTE: We could easily check for this by discarding anything that's larger than the RAM/ROM
268 //       size of the Jaguar console.
269 #warning "!!! FIX !!! Should have sanity checking for ROM size to prevent buffer overflow!"
270         const char ftStrings[5][32] = { "Software", "EEPROM", "Label", "Box Art", "Controller Overlay" };
271         ZIP * zip = openzip(0, 0, zipFile);
272
273         if (zip == NULL)
274         {
275                 WriteLog("FILE: Could not open file '%s'!\n", zipFile);
276                 return 0;
277         }
278
279         zipent * ze;
280         bool found = false;
281
282         // The order is here is important: If the file is found, we need to short-circuit the
283         // readzip() call because otherwise, 'ze' will be pointing to the wrong file!
284         while (!found && readzip(zip))
285         {
286                 ze = &zip->ent;
287
288                 // Here we simply rely on the file extension to tell the truth, but we know
289                 // that extensions lie like sons-a-bitches. So this is naive, we need to do
290                 // something a little more robust to keep bad things from happening here.
291 #warning "!!! Checking for image by extension can be fooled !!!"
292                 if ((type == FT_LABEL) && (CheckExtension(ze->name, ".png") || CheckExtension(ze->name, ".jpg") || CheckExtension(ze->name, ".gif")))
293                 {
294                         found = true;
295                         WriteLog("FILE: Found image file '%s'.\n", ze->name);
296                 }
297
298                 if ((type == FT_SOFTWARE) && (CheckExtension(ze->name, ".j64")
299                         || CheckExtension(ze->name, ".rom") || CheckExtension(ze->name, ".abs")
300                         || CheckExtension(ze->name, ".cof") || CheckExtension(ze->name, ".jag")))
301                 {
302                         found = true;
303                         WriteLog("FILE: Found software file '%s'.\n", ze->name);
304                 }
305
306                 if ((type == FT_EEPROM) && (CheckExtension(ze->name, ".eep") || CheckExtension(ze->name, ".eeprom")))
307                 {
308                         found = true;
309                         WriteLog("FILE: Found EEPROM file '%s'.\n", ze->name);
310                 }
311         }
312
313         uint32 fileSize = 0;
314
315         if (found)
316         {
317                 WriteLog("FILE: Uncompressing...");
318 // Insert file size sanity check here...
319                 buffer = new uint8[ze->uncompressed_size];
320
321                 if (readuncompresszip(zip, ze, (char *)buffer) == 0)
322                 {
323                         fileSize = ze->uncompressed_size;
324                         WriteLog("success! (%u bytes)\n", fileSize);
325                 }
326                 else
327                 {
328                         delete[] buffer;
329                         buffer = NULL;
330                         WriteLog("FAILED!\n");
331                 }
332         }
333         else
334                 // Didn't find what we're looking for...
335                 WriteLog("FILE: Failed to find file of type %s...\n", ftStrings[type]);
336
337         closezip(zip);
338         return fileSize;
339 }
340
341 //
342 // Parse the file type based upon file size and/or headers.
343 //
344 uint32 ParseFileType(uint8 header1, uint8 header2, uint32 size)
345 {
346         // Check headers first...
347
348         // ABS/COFF type 1
349         if (header1 == 0x60 && header2 == 0x1B)
350                 return JST_ABS_TYPE1;
351
352         // ABS/COFF type 2
353         if (header1 == 0x01 && header2 == 0x50)
354                 return JST_ABS_TYPE2;
355
356         // Jag Server
357         if (header1 == 0x60 && header2 == 0x1A)
358                 return JST_JAGSERVER;
359
360         // And if that fails, try file sizes...
361
362         // If the file size is divisible by 1M, we probably have an regular ROM.
363         // We can also check our CRC32 against the internal ROM database to be sure.
364         if ((size % 1048576) == 0)
365                 return JST_ROM;
366
367         // If the file size + 8192 bytes is divisible by 1M, we probably have an
368         // Alpine format ROM.
369         if (((size + 8192) % 1048576) == 0)
370                 return JST_ALPINE;
371
372         // Headerless crap
373         return JST_NONE;
374 }
375
376 //
377 // Check for universal header
378 //
379 bool HasUniversalHeader(uint8 * rom, uint32 romSize)
380 {
381         // Sanity check
382         if (romSize < 8192)
383                 return false;
384
385         for(int i=0; i<8192; i++)
386                 if (rom[i] != universalCartHeader[i])
387                         return false;
388
389         return true;
390 }
391
392 #if 0
393 // Misc. doco
394
395 /*
396 Stubulator ROM vectors...
397 handler 001 at $00E00008
398 handler 002 at $00E008DE
399 handler 003 at $00E008E2
400 handler 004 at $00E008E6
401 handler 005 at $00E008EA
402 handler 006 at $00E008EE
403 handler 007 at $00E008F2
404 handler 008 at $00E0054A
405 handler 009 at $00E008FA
406 handler 010 at $00000000
407 handler 011 at $00000000
408 handler 012 at $00E008FE
409 handler 013 at $00E00902
410 handler 014 at $00E00906
411 handler 015 at $00E0090A
412 handler 016 at $00E0090E
413 handler 017 at $00E00912
414 handler 018 at $00E00916
415 handler 019 at $00E0091A
416 handler 020 at $00E0091E
417 handler 021 at $00E00922
418 handler 022 at $00E00926
419 handler 023 at $00E0092A
420 handler 024 at $00E0092E
421 handler 025 at $00E0107A
422 handler 026 at $00E0107A
423 handler 027 at $00E0107A
424 handler 028 at $00E008DA
425 handler 029 at $00E0107A
426 handler 030 at $00E0107A
427 handler 031 at $00E0107A
428 handler 032 at $00000000
429
430 Let's try setting up the illegal instruction vector for a stubulated jaguar...
431
432                 SET32(jaguar_mainRam, 0x08, 0x00E008DE);
433                 SET32(jaguar_mainRam, 0x0C, 0x00E008E2);
434                 SET32(jaguar_mainRam, 0x10, 0x00E008E6);        // <-- Should be here (it is)...
435                 SET32(jaguar_mainRam, 0x14, 0x00E008EA);//*/
436
437 /*
438 ABS Format sleuthing (LBUGDEMO.ABS):
439
440 000000  60 1B 00 00 05 0C 00 04 62 C0 00 00 04 28 00 00
441 000010  12 A6 00 00 00 00 00 80 20 00 FF FF 00 80 25 0C
442 000020  00 00 40 00
443
444 DRI-format file detected...
445 Text segment size = 0x0000050c bytes
446 Data segment size = 0x000462c0 bytes
447 BSS Segment size = 0x00000428 bytes
448 Symbol Table size = 0x000012a6 bytes
449 Absolute Address for text segment = 0x00802000
450 Absolute Address for data segment = 0x0080250c
451 Absolute Address for BSS segment = 0x00004000
452
453 (CRZDEMO.ABS):
454 000000  01 50 00 03 00 00 00 00 00 03 83 10 00 00 05 3b
455 000010  00 1c 00 03 00 00 01 07 00 00 1d d0 00 03 64 98
456 000020  00 06 8b 80 00 80 20 00 00 80 20 00 00 80 3d d0
457
458 000030  2e 74 78 74 00 00 00 00 00 80 20 00 00 80 20 00 .txt (+36 bytes)
459 000040  00 00 1d d0 00 00 00 a8 00 00 00 00 00 00 00 00
460 000050  00 00 00 00 00 00 00 20
461 000058  2e 64 74 61 00 00 00 00 00 80 3d d0 00 80 3d d0 .dta (+36 bytes)
462 000068  00 03 64 98 00 00 1e 78 00 00 00 00 00 00 00 00
463 000078  00 00 00 00 00 00 00 40
464 000080  2e 62 73 73 00 00 00 00 00 00 50 00 00 00 50 00 .bss (+36 bytes)
465 000090  00 06 8b 80 00 03 83 10 00 00 00 00 00 00 00 00
466 0000a0  00 00 00 00 00 00 00 80
467
468 Header size is $A8 bytes...
469
470 BSD/COFF format file detected...
471 3 sections specified
472 Symbol Table offset = 230160                            ($00038310)
473 Symbol Table contains 1339 symbol entries       ($0000053B)
474 The additional header size is 28 bytes          ($001C)
475 Magic Number for RUN_HDR = 0x00000107
476 Text Segment Size = 7632                                        ($00001DD0)
477 Data Segment Size = 222360                                      ($00036498)
478 BSS Segment Size = 428928                                       ($00068B80)
479 Starting Address for executable = 0x00802000
480 Start of Text Segment = 0x00802000
481 Start of Data Segment = 0x00803dd0
482 */
483 #endif