3e8bb37a2e03577fd07afc5fefd1cab2f56d10ba
[fw/sdcc] / as / link / z80 / lkgg.c
1 /* lkgg.c */
2
3 /*
4  * P. Felber
5  */
6
7 #ifdef GAMEGEAR
8
9 #include <stdio.h>
10 #include <string.h>
11 #include <stdlib.h>
12 #include <string.h>
13 #include "aslink.h"
14
15 #define CARTSIZE ((unsigned long)4*16UL*1024UL)
16 #define NBSEG 8UL
17 #define SEGSIZE (CARTSIZE/NBSEG)
18
19 unsigned char *cart[NBSEG];
20
21 #define ROMSIZE 0x10000UL
22 #define BANKSIZE 0x4000UL
23
24 int current_rom_bank;
25
26 VOID gg(int in)
27 {
28   static int first = 1;
29   unsigned long pos;
30   int i;
31
32   if(first) {
33     for(i = 0; i < NBSEG; i++) {
34       if((cart[i] = malloc(SEGSIZE)) == NULL) {
35         fprintf(stderr, "ERROR: can't allocate %dth segment of memory (%d bytes)\n", i, (int)SEGSIZE);
36         exit(EXIT_FAILURE);
37       }
38       memset(cart[i], 0, SEGSIZE);
39     }
40     first = 0;
41   }
42   if(in) {
43     if(rtcnt > 2) {
44       if(hilo == 0)
45         pos = rtval[0] | (rtval[1]<<8);
46       else
47         pos = rtval[1] | (rtval[0]<<8);
48
49       /* Perform some validity checks */
50       if(pos >= ROMSIZE) {
51         fprintf(stderr, "ERROR: address overflow (addr %lx >= %lx)\n", pos, ROMSIZE);
52         exit(EXIT_FAILURE);
53       }
54       if(current_rom_bank > 1)
55         pos += (current_rom_bank-1)*BANKSIZE;
56       for(i = 2; i < rtcnt; i++) {
57         if(rtflg[i]) {
58           if(pos < CARTSIZE) {
59             if(cart[pos/SEGSIZE][pos%SEGSIZE] != 0)
60               fprintf(stderr, "WARNING: wrote twice at addr %lx (%02X->%02X)\n", pos, rtval[i], cart[pos/SEGSIZE][pos%SEGSIZE]);
61             cart[pos/SEGSIZE][pos%SEGSIZE] = rtval[i];
62           } else {
63             fprintf(stderr, "ERROR: cartridge size overflow (addr %lx >= %lx)\n", pos, CARTSIZE);
64             exit(EXIT_FAILURE);
65           }
66           pos++;
67         }
68       }
69     }
70   } else {
71     /* EOF */
72     /* Patch before calculating the checksum */
73     for(i = 0; i < NBSEG; i++)
74       fwrite(cart[i], 1, SEGSIZE, ofp);
75   }
76 }
77
78 #endif /* GAMEGEAR */