3a2bd651814d4bc6f9fef469d9f6a8b6a93569b3
[ginge.git] / loader / emu.c
1 /*
2  * GINGE - GINGE Is Not Gp2x Emulator
3  * (C) notaz, 2010-2011,2016
4  *
5  * This work is licensed under the MAME license, see COPYING file for details.
6  */
7 // a "gentle" reminder
8 #ifdef __ARM_EABI__
9 #error loader is meant to be OABI!
10 #endif
11 #include <stdio.h>
12 #include <stdlib.h>
13 #include <string.h>
14 #include <alloca.h>
15 #include <ctype.h>
16 #include <sys/types.h>
17 #include <sys/stat.h>
18 #include <fcntl.h>
19 #include <sys/mman.h>
20 #include <sys/types.h>
21 #include <unistd.h>
22 #include <signal.h>
23 #include <asm/ucontext.h>
24 #include <errno.h>
25 #include <time.h>
26 #include <sched.h>
27 #include <sys/resource.h>
28 #include <sys/ioctl.h>
29 #include <sys/syscall.h>
30 #include <linux/soundcard.h>
31 #include <linux/fb.h>
32 #include <linux/futex.h>
33
34 #include "header.h"
35 #include "../common/host_fb.h"
36 #include "../common/cmn.h"
37 #include "syscalls.h"
38 #include "realfuncs.h"
39 #include "llibc.h"
40
41 #if (DBG & 2) && !(DBG & 4)
42 #define LOG_IO_UNK
43 #endif
44 #if (DBG & 4)
45 #define LOG_IO
46 #endif
47 //#define LOG_SEGV
48
49 #ifdef LOG_IO
50 #define iolog log_io
51 #else
52 #define iolog(...)
53 #endif
54
55 #ifdef LOG_IO_UNK
56 #define iolog_unh log_io
57 #else
58 #define iolog_unh(...)
59 #endif
60
61 #ifdef LOG_SEGV
62 #define segvlog g_printf
63 #else
64 #define segvlog(...)
65 #endif
66
67 #if defined(LOG_IO) || defined(LOG_IO_UNK)
68 #include "mmsp2-regs.h"
69 #endif
70
71 typedef unsigned long long u64;
72 typedef unsigned int   u32;
73 typedef unsigned short u16;
74 typedef unsigned char  u8;
75
76 #define THREAD_STACK_SIZE 0x200000
77
78 static int fb_sync_thread_paused;
79 static int fb_sync_thread_futex;
80
81 static int emu_is_dl;
82
83 static struct {
84   u32 dstctrl;
85   u32 dstaddr;
86   u32 dststride;
87   u32 srcctrl;
88   u32 srcaddr;          //
89   u32 srcstride;
90   u32 srcforcolor;
91   u32 srcbackcolor;
92   u32 patctrl;          //
93   u32 patforcolor;
94   u32 patbackcolor;
95   u32 size;
96   u32 ctrl;             //
97   u32 run;
98   u32 intc;
99   u32 srcfifo;
100 } blitter;
101
102 #define SRCCTRL_INVIDEO         (1 << 8)
103 #define SRCCTRL_SRCENB          (1 << 7)
104 #define CTRL_TRANSPARENCYENB    (1 << 11)
105
106 static struct {
107   // mmsp2
108   u16 mlc_stl_cntl;
109   union {
110     u32 mlc_stl_adr; // mlcaddress for pollux
111     struct {
112       u16 mlc_stl_adrl;
113       u16 mlc_stl_adrh;
114     };
115   };
116   u16 mlc_stl_pallt_a;
117   union {
118     u16 mlc_stl_pallt_d[256*2];
119     u32 mlc_stl_pallt_d32[256];
120   };
121
122   // pollux
123   u32 mlccontrol;
124   u16 mlcpalette[256];
125
126   // state
127   void *umem;
128   u32 old_mlc_stl_adr;
129   u32 btn_state; // as seen through /dev/GPIO: 0PVdVu YXBA RLSeSt 0Ri0Dn 0Le0Up
130   struct {
131     u32 width, height;
132     u32 stride;
133     u32 bpp;
134     u32 dirty_pal:2;
135   } v;
136 } mmsp2;
137 #define pollux mmsp2 // so that code doesn't look that weird
138 enum {
139   DIRTY_PAL_MMSP2 = 1,
140   DIRTY_PAL_POLLUX = 2,
141 };
142
143
144 #if defined(LOG_IO) || defined(LOG_IO_UNK)
145 static void log_io(const char *pfx, u32 a, u32 d, int size)
146 {
147   const char *fmt, *reg = "";
148   switch (size) {
149   case  8: fmt = "%s %08x       %02x %s\n"; d &= 0xff; break;
150   case 32: fmt = "%s %08x %08x %s\n";       break;
151   default: fmt = "%s %08x     %04x %s\n";   d &= 0xffff; break;
152   }
153
154   if ((a & ~0xffff) == 0x7f000000)
155     reg = regnames[a & 0xffff];
156
157   g_printf(fmt, pfx, a, d, reg);
158 }
159 #endif
160
161 static void memset16(void *dst, u32 pattern, int count)
162 {
163   u32 *dl;
164   u16 *d;
165   
166   d = (u16 *)((long)dst & ~1);
167   if ((long)d & 2) {
168     *d++ = pattern;
169     count--;
170   }
171   dl = (void *)d;
172   pattern |= pattern << 16;
173
174   while (count >= 2) {
175     *dl++ = pattern;
176     count -= 2;
177   }
178   if (count)
179     *(u16 *)dl = pattern;
180 }
181
182 static void blt_tr(void *dst, void *src, u32 trc, int w)
183 {
184   u16 *d = (u16 *)((long)dst & ~1);
185   u16 *s = (u16 *)((long)src & ~1);
186
187   // XXX: optimize
188   for (; w > 0; d++, s++, w--)
189     if (*s != trc)
190       *d = *s;
191 }
192
193 #define dump_blitter() \
194 { \
195   u32 *r = &blitter.dstctrl; \
196   int i; \
197   for (i = 0; i < 4*4; i++, r++) { \
198     g_printf("%08x ", *r); \
199     if ((i & 3) == 3) \
200       g_printf("\n"); \
201   } \
202 }
203
204 static void *uppermem_lookup(u32 addr, u8 **mem_end)
205 {
206   // XXX: maybe support mirroring?
207   if ((addr & 0xfe000000) != 0x02000000)
208     return NULL;
209
210   *mem_end = (u8 *)mmsp2.umem + 0x02000000;
211   return (u8 *)mmsp2.umem - 0x02000000 + addr;
212 }
213
214 static void blitter_do(void)
215 {
216   u8 *dst, *dste, *src = NULL, *srce = NULL;
217   int w, h, sstrd, dstrd;
218   int to_screen = 0;
219   u32 bpp, addr;
220
221   w = blitter.size & 0x7ff;
222   h = (blitter.size >> 16) & 0x7ff;
223   sstrd = blitter.srcstride;
224   dstrd = blitter.dststride;
225
226   // XXX: need to confirm this..
227   addr = (blitter.dstaddr & ~3) | ((blitter.dstctrl & 0x1f) >> 3);
228
229   // use dst bpp.. How does it do blits with different src bpp?
230   bpp = (blitter.dstctrl & 0x20) ? 16 : 8;
231
232   // maybe the screen?
233   if (((w == 320 && h == 240) || // blit whole screen
234        (w * h >= 320*240/2)) &&  // ..or at least half of the area
235        mmsp2.mlc_stl_adr <= addr && addr < mmsp2.mlc_stl_adr + 320*240*2)
236     to_screen = 1;
237
238   dst = uppermem_lookup(addr, &dste);
239
240   // XXX: assume fill if no SRCENB, but it could be pattern blit..
241   if (blitter.srcctrl & SRCCTRL_SRCENB) {
242     if (!(blitter.srcctrl & SRCCTRL_INVIDEO))
243       goto bad_blit;
244
245     addr = (blitter.srcaddr & ~3) | ((blitter.srcctrl & 0x1f) >> 3);
246     src = uppermem_lookup(addr, &srce);
247     if (src == NULL)
248       goto bad_blit;
249
250     if (src + sstrd * h > srce) {
251       err("blit %08x->%08x %dx%d did not fit src\n",
252         blitter.srcaddr, blitter.dstaddr, w, h);
253       h = (srce - src) / sstrd;
254     }
255   }
256
257   if (dst == NULL)
258     goto bad_blit;
259
260   if (dst + dstrd * h > dste) {
261     err("blit %08x->%08x %dx%d did not fit dst\n",
262       blitter.srcaddr, blitter.dstaddr, w, h);
263     h = (dste - dst) / dstrd;
264   }
265
266   if (src != NULL) {
267     // copy
268     if (bpp == 16 && (blitter.ctrl & CTRL_TRANSPARENCYENB)) {
269       u32 trc = blitter.ctrl >> 16;
270       for (; h > 0; h--, dst += dstrd, src += sstrd)
271         blt_tr(dst, src, trc, w);
272     }
273     else {
274       for (; h > 0; h--, dst += dstrd, src += sstrd)
275         memcpy(dst, src, w * bpp / 8);
276     }
277   }
278   else {
279     // fill. Assume the pattern is cleared and bg color is used
280     u32 bgc = blitter.patbackcolor & 0xffff;
281     if (bpp == 16) {
282       for (; h > 0; h--, dst += dstrd)
283         memset16(dst, bgc, w);
284     }
285     else {
286       for (; h > 0; h--, dst += dstrd)
287         memset(dst, bgc, w); // bgc?
288     }
289   }
290
291   if (to_screen) {
292     fb_sync_thread_futex = 1;
293     g_futex_raw(&fb_sync_thread_futex, FUTEX_WAKE, 1, NULL);
294   }
295   return;
296
297 bad_blit:
298   err("blit %08x->%08x %dx%d translated to %p->%p\n",
299     blitter.srcaddr, blitter.dstaddr, w, h, src, dst);
300   dump_blitter();
301 }
302
303 // FIXME: pass real dimensions to blitters
304 static void mlc_flip(void *src, int bpp, int stride)
305 {
306   static int old_bpp;
307
308   // only pass pal to host if it's dirty
309   if (bpp <= 8 && mmsp2.v.dirty_pal) {
310     if (mmsp2.v.dirty_pal == DIRTY_PAL_MMSP2)
311       host_video_update_pal32(mmsp2.mlc_stl_pallt_d32);
312     else
313       host_video_update_pal16(mmsp2.mlcpalette);
314     mmsp2.v.dirty_pal = 0;
315   }
316
317   if (bpp != old_bpp) {
318     host_video_change_bpp(bpp);
319     old_bpp = bpp;
320   }
321
322   switch (bpp) {
323   case  4:
324     host_video_blit4(src, 320, 240, stride);
325     break;
326
327   case  8:
328     host_video_blit8(src, 320, 240, stride);
329     break;
330
331   case 16:
332     host_video_blit16(src, 320, 240, stride);
333     break;
334
335   case 24:
336     // TODO
337     break;
338   }
339 }
340
341 static void *fb_sync_thread(void *arg)
342 {
343   unsigned long sigmask[2] = { ~0ul, ~0ul };
344   struct timespec ts = { 0, 0 };
345   int invalid_fb_addr = 1;
346   int manual_refresh = 0;
347   int frame_counter = 0;
348   int wait_ret;
349
350   // this thread can't run any signal handlers since the
351   // app's stack/tls stuff will never be set up here
352   sigmask[0] &= ~(1ul << (SIGSEGV - 1));
353   g_rt_sigprocmask_raw(SIG_SETMASK, sigmask, NULL, sizeof(sigmask));
354
355   //ret = setpriority(PRIO_PROCESS, 0, -1);
356   //log("setpriority %d\n", ret);
357
358   // tell the main thread we're done init
359   fb_sync_thread_futex = 0;
360   g_futex_raw(&fb_sync_thread_futex, FUTEX_WAKE, 1, NULL);
361
362   while (1) {
363     u8 *gp2x_fb, *gp2x_fb_end;
364
365     wait_ret = g_futex_raw(&fb_sync_thread_futex, FUTEX_WAIT, 0, &ts);
366
367     // this is supposed to be done atomically, but to make life
368     // easier ignore it for now, race impact is low anyway
369     fb_sync_thread_futex = 0;
370
371     if (wait_ret != 0 && wait_ret != -EWOULDBLOCK
372         && wait_ret != -ETIMEDOUT)
373     {
374       err("fb_thread: futex error: %d\n", wait_ret);
375       sleep(1);
376       goto check_keys;
377     }
378     if (fb_sync_thread_paused) {
379       ts.tv_nsec = 100000000;
380       goto check_keys;
381     }
382
383     if (wait_ret == 0) {
384       ts.tv_nsec = 50000000;
385       manual_refresh++;
386       if (manual_refresh == 2)
387         dbg("fb_thread: switch to manual refresh\n");
388     } else {
389       ts.tv_nsec = 16666667;
390       if (manual_refresh > 1)
391         dbg("fb_thread: switch to auto refresh\n");
392       manual_refresh = 0;
393     }
394
395     gp2x_fb = uppermem_lookup(mmsp2.mlc_stl_adr, &gp2x_fb_end);
396     if (gp2x_fb == NULL || gp2x_fb + 320*240 * mmsp2.v.bpp / 8 > gp2x_fb_end) {
397       if (!invalid_fb_addr) {
398         err("fb_thread: %08x is out of range\n", mmsp2.mlc_stl_adr);
399         invalid_fb_addr = 1;
400       }
401       continue;
402     }
403
404     invalid_fb_addr = 0;
405     mlc_flip(gp2x_fb, mmsp2.v.bpp, mmsp2.v.stride);
406
407     frame_counter++;
408     if (frame_counter & 0x0f)
409       continue;
410
411 check_keys:
412     // this is to check for kill key, in case main thread hung
413     // or something else went wrong.
414     pollux.btn_state = host_read_btns();
415   }
416 }
417
418 static void fb_thread_pause(void)
419 {
420   fb_sync_thread_paused = 1;
421   // wait until it finishes last refresh
422   // that it might be doing now
423   usleep(10000);
424 }
425
426 static void fb_thread_resume(void)
427 {
428   fb_sync_thread_paused = 0;
429 }
430
431 static u32 xread32_io_cmn(u32 a, u32 *handled)
432 {
433   u32 d = 0;
434
435   *handled = 1;
436   switch (a) {
437   // Wiz stuff
438   case 0x402c: // MLCVSTRIDE0
439   case 0x4060: // MLCVSTRIDE1
440     d = pollux.v.stride;
441     break;
442   case 0x4038: // MLCADDRESS0
443   case 0x406c: // MLCADDRESS1
444     d = pollux.mlc_stl_adr;
445     break;
446   // wiz_lib reads:
447   //  ???? ???? YXBA DURiLe ???? VdVuMS LR?? ????
448   // |     GPIOC[31:16]    |    GPIOB[31:16]     |
449   case 0xa058: // GPIOBPAD
450     d =  (pollux.btn_state >> 1) & 0x0100;
451     d |= (pollux.btn_state << 1) & 0x0200;
452     d |= (pollux.btn_state >> 3) & 0x0080;
453     d |= (pollux.btn_state >> 5) & 0x0040;
454     d |= (pollux.btn_state >> 6) & 0x0c00;
455     d <<= 16;
456     d = ~d;
457     break;
458   case 0xa098: // GPIOCPAD
459     pollux.btn_state = host_read_btns();
460     d =  (pollux.btn_state >> 8) & 0x00f0;
461     d |= (pollux.btn_state >> 1) & 0x0008;
462     d |= (pollux.btn_state << 2) & 0x0004;
463     d |= (pollux.btn_state >> 5) & 0x0002;
464     d |= (pollux.btn_state >> 2) & 0x0001;
465     d <<= 16;
466     d = ~d;
467     break;
468   default:
469     *handled = 0;
470     break;
471   }
472
473   return d;
474 }
475
476 static u32 xread8(u32 a)
477 {
478   iolog("r8 ", a, 0, 8);
479   iolog_unh("r8 ", a, 0, 8);
480   return 0;
481 }
482
483 static u32 xread16(u32 a)
484 {
485   static u32 fudge, old_a;
486   u32 d = 0, t;
487
488   if ((a & 0xffff0000) == 0x7f000000) {
489     u32 a_ = a & 0xffff;
490     switch (a_) {
491     case 0x0910: // FPLL
492     case 0x0912:
493       d = 0x9407;
494       break;
495     // minilib reads as:
496     //  0000 P000 VuVd00 0000 YXBA RLSeSt 0Ri0D 0Le0U
497     // |        GPIOD        |GPIOC[8:15]|GPIOM[0:7] |
498     // /dev/GPIO:
499     //             ... 0PVdVu ...
500     case 0x1184: // GPIOC
501       d = ~mmsp2.btn_state & 0xff00;
502       d |= 0x00ff;
503       break;
504     case 0x1186: // GPIOD
505       t = ~mmsp2.btn_state;
506       d  = (t >> 9)  & 0x0080;
507       d |= (t >> 11) & 0x0040;
508       d |= (t >> 7)  & 0x0800;
509       d |= 0x373b;
510       break;
511     case 0x1198: // GPIOM
512       mmsp2.btn_state = host_read_btns();
513       d = ~mmsp2.btn_state & 0xff;
514       d |= 0x01aa;
515       break;
516     case 0x1836: // reserved
517       d = 0x2330;
518       break;
519     case 0x2816: // DPC_X_MAX
520       d = 319;
521       break;
522     case 0x2818: // DPC_Y_MAX
523       d = 239;
524       break;
525     case 0x28da:
526       d = mmsp2.mlc_stl_cntl;
527       break;
528     case 0x290e:
529     case 0x2912:
530       d = mmsp2.mlc_stl_adrl;
531       break;
532     case 0x2910:
533     case 0x2914:
534       d = mmsp2.mlc_stl_adrh;
535       break;
536     case 0x2958:
537       d = mmsp2.mlc_stl_pallt_a;
538       break;
539
540     default:
541       d = xread32_io_cmn(a_, &t);
542       if (!t)
543         goto unk;
544       if (!(a_ & 2))
545         d >>= 16;
546       break;
547     }
548     goto out;
549   }
550
551 unk:
552   if (a == old_a) {
553     d = fudge;
554     fudge = ~fudge;
555   }
556   old_a = a;
557   iolog_unh("r16", a, d & 0xffff, 16);
558
559 out:
560   d &= 0xffff;
561   iolog("r16", a, d, 16);
562   return d;
563 }
564
565 static u32 xread32(u32 a)
566 {
567   u32 d = 0;
568   if ((a & 0xfff00000) == 0x7f000000) {
569     u32 a_ = a & 0xffff;
570     struct timespec ts;
571     u64 t64;
572     u32 t;
573
574     switch (a_) {
575     case 0x0a00: // TCOUNT, 1/7372800s
576       g_clock_gettime_raw(CLOCK_REALTIME, &ts);
577       t64 = (u64)ts.tv_sec * 1000000000 + ts.tv_nsec;
578       // t * 7372800.0 / 1000000000 * 0x100000000 ~= t * 31665935
579       t64 *= 31665935;
580       d = t64 >> 32;
581       break;
582
583     default:
584       d = xread32_io_cmn(a_, &t);
585       if (!t)
586         goto unh;
587       break;
588     }
589     goto out;
590   }
591   if ((a & 0xfff00000) == 0x7f100000) {
592     u32 *bl = &blitter.dstctrl;
593     u32 a_ = a & 0xfff;
594     if (a_ < 0x40) {
595       d = bl[a_ / 4];
596       if (a_ == 0x34)
597         d = 0; // not busy
598       goto out;
599     }
600   }
601
602 unh:
603   iolog_unh("r32", a, d, 32);
604
605 out:
606   iolog("r32", a, d, 32);
607   return d;
608 }
609
610 static void xwrite8(u32 a, u32 d)
611 {
612   iolog("w8 ", a, d, 8);
613   iolog_unh("w8 ", a, d, 8);
614 }
615
616 static void xwrite16(u32 a, u32 d)
617 {
618   iolog("w16", a, d, 16);
619   if ((a & 0xfff00000) == 0x7f000000) {
620     u32 a_ = a & 0xffff;
621     switch (a_) {
622       case 0x28da: {
623         int mode;
624         mmsp2.mlc_stl_cntl = d | 0xaa;
625         mode = (d >> 9) & 3;
626         mmsp2.v.bpp = mode ? mode * 8 : 4;
627         break;
628       }
629       case 0x290c:
630         mmsp2.v.stride = d;
631         return;
632       case 0x290e:
633       case 0x2910:
634         // odd addresses don't affect LCD. What about TV?
635         return;
636       case 0x2912:
637         mmsp2.mlc_stl_adrl = d;
638         return;
639       case 0x2914:
640         mmsp2.mlc_stl_adrh = d;
641         if (mmsp2.mlc_stl_adr != mmsp2.old_mlc_stl_adr) {
642           // ask for refresh
643           fb_sync_thread_futex = 1;
644           g_futex_raw(&fb_sync_thread_futex, FUTEX_WAKE, 1, NULL);
645         }
646         mmsp2.old_mlc_stl_adr = mmsp2.mlc_stl_adr;
647         return;
648       case 0x2958: // MLC_STL_PALLT_A
649         mmsp2.mlc_stl_pallt_a = d & 0x1ff;
650         return;
651       case 0x295a: // MLC_STL_PALLT_D
652         mmsp2.mlc_stl_pallt_d[mmsp2.mlc_stl_pallt_a++] = d;
653         mmsp2.mlc_stl_pallt_a &= 0x1ff;
654         mmsp2.v.dirty_pal = DIRTY_PAL_MMSP2;
655         return;
656     }
657   }
658   iolog_unh("w16", a, d, 16);
659 }
660
661 static void xwrite32(u32 a, u32 d)
662 {
663   iolog("w32", a, d, 32);
664
665   if ((a & 0xfff00000) == 0x7f000000) {
666     u32 a_ = a & 0xffff;
667     switch (a_) {
668     // GP2X
669     case 0x295a: // MLC_STL_PALLT_D
670       // special unaligned 32bit write, allegro seems to rely on it
671       mmsp2.mlc_stl_pallt_d[mmsp2.mlc_stl_pallt_a++ & 0x1ff] = d;
672       mmsp2.mlc_stl_pallt_d[mmsp2.mlc_stl_pallt_a++ & 0x1ff] = d >> 16;
673       mmsp2.mlc_stl_pallt_a &= 0x1ff;
674       mmsp2.v.dirty_pal = DIRTY_PAL_MMSP2;
675       return;
676     // Wiz
677     case 0x4024: // MLCCONTROL0
678     case 0x4058: // MLCCONTROL1
679       pollux.mlccontrol = d;
680       if (!(d & 0x20))
681         return; // layer not enabled
682       if ((d >> 16) == 0x443A)
683         pollux.v.bpp = 8;
684       else
685         pollux.v.bpp = 16;
686       return;
687     case 0x402c: // MLCVSTRIDE0
688     case 0x4060: // MLCVSTRIDE1
689       pollux.v.stride = d;
690       return;
691     case 0x4038: // MLCADDRESS0
692     case 0x406c: // MLCADDRESS1
693       pollux.mlc_stl_adr = d;
694       if (d != mmsp2.old_mlc_stl_adr) {
695         // ask for refresh
696         fb_sync_thread_futex = 1;
697         g_futex_raw(&fb_sync_thread_futex, FUTEX_WAKE, 1, NULL);
698       }
699       mmsp2.old_mlc_stl_adr = d;
700       return;
701     case 0x403c: // MLCPALETTE0
702     case 0x4070: // MLCPALETTE1
703       pollux.mlcpalette[d >> 24] = d;
704       pollux.v.dirty_pal = DIRTY_PAL_POLLUX;
705       return;
706     }
707   }
708   if ((a & 0xfff00000) == 0x7f100000) {
709     u32 *bl = &blitter.dstctrl;
710     u32 a_ = a & 0xfff;
711     if (a_ < 0x40) {
712       bl[a_ / 4] = d;
713       if (a_ == 0x34 && (d & 1))
714         blitter_do();
715       return;
716     }
717   }
718   iolog_unh("w32", a, d, 32);
719 }
720
721 #define LINKPAGE_SIZE 0x1000
722 #define LINKPAGE_COUNT 4
723 #define LINKPAGE_ALLOC (LINKPAGE_SIZE * LINKPAGE_COUNT)
724
725 struct op_context {
726   u32 pc;
727   u32 op;
728   u32 code[0];
729 };
730
731 struct op_linkpage {
732   u32 *code_ptr;
733   void (*handler)(struct op_context *op_ctx);
734   u32 code[0];
735 };
736
737 struct op_stackframe {
738   u32 saved_regs[15];
739   u32 cpsr;
740 };
741
742 static struct op_linkpage *g_linkpages[2];
743 static int g_linkpage_count;
744
745 enum opcond {
746   C_EQ, C_NE, C_CS, C_CC, C_MI, C_PL, C_VS, C_VC,
747   C_HI, C_LS, C_GE, C_LT, C_GT, C_LE, C_AL,
748 };
749 enum cpsr_cond {
750   CPSR_N = (1u << 31),
751   CPSR_Z = (1u << 30),
752   CPSR_C = (1u << 29),
753   CPSR_V = (1u << 28),
754 };
755
756 #define BIT_SET(v, b) (v & (1 << (b)))
757
758 void emu_handle_op(struct op_context *op_ctx, struct op_stackframe *sframe)
759 {
760   u32 *regs = sframe->saved_regs;
761   u32 cpsr = sframe->cpsr;
762   u32 op = op_ctx->op;
763   u32 t, shift, ret, addr;
764   int i, rn, rd, cond;
765
766   cond = (op & 0xf0000000) >> 28;
767   rd = (op & 0x0000f000) >> 12;
768   rn = (op & 0x000f0000) >> 16;
769
770   if (cond != 0x0e) {
771     switch (cond) {
772     case C_EQ: if ( (cpsr & CPSR_Z)) break; return;
773     case C_NE: if (!(cpsr & CPSR_Z)) break; return;
774     case C_CS: if ( (cpsr & CPSR_C)) break; return;
775     case C_CC: if (!(cpsr & CPSR_C)) break; return;
776     case C_MI: if ( (cpsr & CPSR_N)) break; return;
777     case C_PL: if (!(cpsr & CPSR_N)) break; return;
778     case C_VS: if ( (cpsr & CPSR_V)) break; return;
779     case C_VC: if (!(cpsr & CPSR_V)) break; return;
780     default:
781       goto unhandled;
782     }
783   }
784
785   if ((op & 0x0f200090) == 0x01000090) { // AM3: LDRH, STRH
786     if (!BIT_SET(op, 5)) // !H
787       goto unhandled;
788     if (BIT_SET(op, 6) && !BIT_SET(op, 20)) // S && !L
789       goto unhandled;
790
791     if (BIT_SET(op, 22))                // imm offset
792       t = ((op & 0xf00) >> 4) | (op & 0x0f);
793     else                                // reg offset
794       t = regs[op & 0x000f];
795
796     if (!BIT_SET(op, 23))
797       t = -t;
798     addr = regs[rn] + t;
799
800     if (BIT_SET(op, 20)) { // Load
801       ret = xread16(addr);
802       if (BIT_SET(op, 6)) { // S
803         ret <<= 16;
804         ret = (signed int)ret >> 16;
805       }
806       regs[rd] = ret;
807     }
808     else
809       xwrite16(addr, regs[rd]);
810   }
811   else if ((op & 0x0c000000) == 0x04000000) { // load/store word/byte
812     if (BIT_SET(op, 21))
813       goto unhandled;                   // unprivileged
814     if (BIT_SET(op, 25)) {              // reg offs
815       if (BIT_SET(op, 4))
816         goto unhandled;                 // nah it's media
817
818       t = regs[op & 0x000f];
819       shift = (op & 0x0f80) >> 7;
820       switch ((op & 0x0060) >> 5) {
821         case 0: t = t << shift; break;
822         case 1: t = t >> (shift + 1); break;
823         case 2: t = (signed int)t >> (shift + 1); break;
824         case 3: goto unhandled; // I'm just lazy
825       }
826     }
827     else                                // imm offs
828       t = op & 0x0fff;
829
830     if (!BIT_SET(op, 23))
831       t = -t;
832
833     addr = regs[rn];
834     if (BIT_SET(op, 24))   // pre-indexed
835       addr += t;
836     if (!BIT_SET(op, 24) || BIT_SET(op, 21))
837       regs[rn] += t;       // writeback
838
839     if (BIT_SET(op, 20)) { // Load
840       if (BIT_SET(op, 22)) // Byte
841         ret = xread8(addr);
842       else
843         ret = xread32(addr);
844       regs[rd] = ret;
845     }
846     else {
847       if (BIT_SET(op, 22)) // Byte
848         xwrite8(addr, regs[rd]);
849       else
850         xwrite32(addr, regs[rd]);
851     }
852   }
853   else
854     goto unhandled;
855
856 #if 0
857   if (addr != addr_check) {
858     fprintf(stderr, "bad calculated addr: %08x vs %08x\n", addr, addr_check);
859     abort();
860   }
861 #endif
862   return;
863
864 unhandled:
865   err("unhandled IO op %08x @ %08x\n", op, op_ctx->pc);
866   for (i = 0; i < 8-1; i++)
867     err(" r%d=%08x  r%-2d=%08x\n", i, regs[i], i+8, regs[i+8]);
868   err(" r%d=%08x cpsr=%08x\n", i, regs[i], cpsr);
869   abort();
870 }
871
872 static u32 make_offset12(u32 *pc, u32 *target)
873 {
874   int lp_offs, u = 1;
875
876   lp_offs = (char *)target - (char *)pc - 2*4;
877   if (lp_offs < 0) {
878     lp_offs = -lp_offs;
879     u = 0;
880   }
881   if (lp_offs >= LINKPAGE_SIZE) {
882     err("linkpage too far: %d\n", lp_offs);
883     abort();
884   }
885
886   return (u << 23) | lp_offs;
887 }
888
889 static u32 make_jmp(u32 *pc, u32 *target, int bl)
890 {
891   int jmp_val;
892
893   jmp_val = target - pc - 2;
894   if (jmp_val < (int)0xff800000 || jmp_val > 0x007fffff) {
895     err("jump out of range (%p -> %p)\n", pc, target);
896     abort();
897   }
898
899   return 0xea000000 | (bl << 24) | (jmp_val & 0x00ffffff);
900 }
901
902 static void emit_op(struct op_linkpage *linkpage, u32 op)
903 {
904   *linkpage->code_ptr++ = op;
905 }
906
907 static void emit_op_io(struct op_linkpage *linkpage,
908   u32 op, u32 *target)
909 {
910   op |= make_offset12(linkpage->code_ptr, target);
911   emit_op(linkpage, op);
912 }
913
914 static void init_linkpage(struct op_linkpage *linkpage)
915 {
916   linkpage->handler = emu_call_handle_op;
917   linkpage->code_ptr = linkpage->code;
918 }
919
920 static void segv_sigaction(int num, siginfo_t *info, void *ctx)
921 {
922   extern char _init, _end;
923   struct ucontext *context = ctx;
924   u32 *regs = (u32 *)&context->uc_mcontext.arm_r0;
925   u32 *pc = (u32 *)regs[15];
926   u32 self_start, self_end;
927   struct op_linkpage *lp = NULL;
928   struct op_context *op_ctx;
929   int i, ret, lp_i, lp_size;
930
931   self_start = (u32)&_init & ~0xfff;
932   self_end = (u32)&_end;
933
934   if ((self_start <= regs[15] && regs[15] <= self_end) ||           // PC is in our segment or
935      !((regs[15] ^ (u32)g_linkpages[0]) & ~(LINKPAGE_ALLOC - 1)) || // .. in linkpage
936       ((long)info->si_addr & 0xffe00000) != 0x7f000000)             // faulting not where expected
937   {
938     // real crash - time to die
939     err("segv %d %p @ %08x\n", info->si_code, info->si_addr, regs[15]);
940     for (i = 0; i < 8; i++)
941       dbg(" r%d=%08x r%-2d=%08x\n", i, regs[i], i+8, regs[i+8]);
942     signal(num, SIG_DFL);
943     raise(num);
944     return;
945   }
946   segvlog("segv %d %p @ %08x\n", info->si_code, info->si_addr, regs[15]);
947
948   // find nearby linkpage
949   for (lp_i = 0; lp_i < ARRAY_SIZE(g_linkpages); lp_i++) {
950     if (g_linkpages[lp_i] == NULL)
951       continue;
952     i = g_linkpages[lp_i]->code_ptr + 2 - pc - 2;
953     if ((int)0xff800000 <= i && i <= 0x007fffff) {
954       lp = g_linkpages[lp_i];
955       break;
956     }
957   }
958
959   if (lp == NULL) {
960     err("fatal: no nearby linkpage for %08x\n", regs[15]);
961     abort();
962   }
963
964   if (emu_is_dl) {
965     ret = mprotect((void *)((long)pc & ~0xfff), 0x1000, PROT_READ|PROT_WRITE|PROT_EXEC);
966     if (ret != 0)
967       perror("warning: mprotect");
968   }
969
970   // spit PC and op
971   op_ctx = (void *)lp->code_ptr;
972   op_ctx->pc = (u32)pc;
973   op_ctx->op = *pc;
974   lp->code_ptr = &op_ctx->code[0];
975
976   // emit jump to code ptr
977   *pc = make_jmp(pc, lp->code_ptr, 0);
978
979   // generate code:
980   emit_op   (lp, 0xe50d0000 + 0xf00 - 4 * 0);                        // str r0, [sp, #(-0xf00 + r0_offs)]
981   emit_op   (lp, 0xe50de000 + 0xf00 - 4 * 14);                       // str lr, [sp, #(-0xf00 + lr_offs)]
982   emit_op   (lp, 0xe24f0000 + (lp->code_ptr - (u32 *)op_ctx + 2) * 4); // sub r0, pc, #op_ctx
983   emit_op   (lp, 0xe1a0e00f);                                        // mov lr, pc
984   emit_op_io(lp, 0xe51ff000, (u32 *)&lp->handler);                   // ldr pc, =handle_op
985   emit_op   (lp, 0xe51de000 + 0xf00 - 4 * 14);                       // ldr lr, [sp, #(-0xf00 + lr_offs)]
986   emit_op   (lp, make_jmp(lp->code_ptr, pc + 1, 0));                 // jmp <back>
987
988   // sync caches
989   sys_cacheflush(pc, pc + 1);
990   sys_cacheflush(lp, lp->code_ptr);
991
992   lp_size = (char *)lp->code_ptr - (char *)lp;
993   segvlog("code #%d %d/%d\n", g_linkpage_count, lp_size, LINKPAGE_SIZE);
994
995   if (lp_size + 14*4 > LINKPAGE_SIZE) {
996     g_linkpage_count++;
997     if (g_linkpage_count >= LINKPAGE_COUNT) {
998       err("too many linkpages needed\n");
999       abort();
1000     }
1001     g_linkpages[lp_i] = (void *)((char *)g_linkpages[lp_i] + LINKPAGE_SIZE);
1002     init_linkpage(g_linkpages[lp_i]);
1003   }
1004   //handle_op(regs[15], op, regs, (u32)info->si_addr);
1005   //regs[15] += 4;
1006 }
1007
1008 void emu_init(void *map_bottom[2], int is_dl)
1009 {
1010   sigaction_t segv_action = {
1011     .sa_sigaction = segv_sigaction,
1012     .sa_flags = SA_SIGINFO,
1013   };
1014   void *pret;
1015   int i, ret;
1016
1017 #ifdef PND
1018   if (geteuid() == 0) {
1019     err("don't try to run as root, device registers or memory "
1020         "might get trashed crashing the OS or even damaging the device.\n");
1021     exit(1);
1022   }
1023 #endif
1024
1025   emu_is_dl = is_dl;
1026
1027   for (i = 0; i < 2; i++) {
1028     if (map_bottom[i] == NULL)
1029       continue;
1030     g_linkpages[i] = (void *)(((u32)map_bottom[i] - LINKPAGE_ALLOC) & ~0xfff);
1031     pret = mmap(g_linkpages[i], LINKPAGE_ALLOC, PROT_READ|PROT_WRITE,
1032                 MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0);
1033     if (pret != g_linkpages[i]) {
1034       err("linkpage alloc @ %p: ", g_linkpages[i]);
1035       perror(NULL);
1036       exit(1);
1037     }
1038     log("linkpages @ %p\n", g_linkpages[i]);
1039     init_linkpage(g_linkpages[i]);
1040   }
1041
1042   // host stuff
1043   ret = host_init();
1044   if (ret != 0) {
1045     err("can't init host\n");
1046     exit(1);
1047   }
1048
1049   ret = host_video_init(NULL, 0);
1050   if (ret != 0) {
1051     err("can't init host video\n");
1052     exit(1);
1053   }
1054
1055   // TODO: check if this really fails on Wiz..
1056   mmsp2.umem = mmap(NULL, 0x2000000, PROT_READ|PROT_WRITE|PROT_EXEC,
1057                     MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
1058 #ifdef WIZ
1059   if (mmsp2.umem == MAP_FAILED) {
1060     // we are short on memmory on Wiz, need special handling
1061     extern void *host_mmap_upper(void);
1062     mmsp2.umem = host_mmap_upper();
1063   }
1064 #endif
1065   if (mmsp2.umem == MAP_FAILED) {
1066     perror(PFX "mmap upper mem");
1067     exit(1);
1068   }
1069
1070   pret = mmap(NULL, THREAD_STACK_SIZE, PROT_READ|PROT_WRITE|PROT_EXEC,
1071               MAP_PRIVATE|MAP_ANONYMOUS|MAP_GROWSDOWN, -1, 0);
1072   if (mmsp2.umem == MAP_FAILED) {
1073     perror(PFX "mmap thread stack");
1074     exit(1);
1075   }
1076   fb_sync_thread_futex = 1;
1077   ret = g_clone(CLONE_VM | CLONE_FS | CLONE_FILES
1078                 | CLONE_SIGHAND | CLONE_THREAD,
1079                 (char *)pret + THREAD_STACK_SIZE, 0, 0, 0,
1080                 fb_sync_thread);
1081   if (ret == 0 || ret == -1) {
1082     perror(PFX "start fb thread");
1083     exit(1);
1084   }
1085   g_futex_raw(&fb_sync_thread_futex, FUTEX_WAIT, 1, NULL);
1086
1087   // defaults
1088   mmsp2.mlc_stl_adr = 0x03101000; // fb2 is at 0x03381000
1089   mmsp2.mlc_stl_cntl = 0x4ab; // 16bpp, region 1 active
1090   mmsp2.v.width = 320;
1091   mmsp2.v.height = 240;
1092   mmsp2.v.stride = 320*2;
1093   mmsp2.v.bpp = 16;
1094   mmsp2.v.dirty_pal = 1;
1095
1096   sigemptyset(&segv_action.sa_mask);
1097   sigaction(SIGSEGV, &segv_action, NULL);
1098 }
1099
1100 static long emu_mmap_dev(unsigned int length, int prot, int flags, unsigned int offset)
1101 {
1102   u8 *umem, *umem_end;
1103
1104   // SoC regs
1105   if ((offset & ~0x1ffff) == 0xc0000000) {
1106     return g_mmap2_raw((void *)0x7f000000, length, PROT_NONE,
1107       MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_NORESERVE, -1, 0);
1108   }
1109   // MMSP2 blitter
1110   if ((offset & ~0xffff) == 0xe0020000) {
1111     return g_mmap2_raw((void *)0x7f100000, length, PROT_NONE,
1112       MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_NORESERVE, -1, 0);
1113   }
1114   // upper mem
1115   if ((offset & 0xfe000000) != 0x02000000) {
1116     err("unexpected devmem mmap @ %08x\n", offset);
1117     return -EINVAL;
1118   }
1119
1120   umem = uppermem_lookup(offset, &umem_end);
1121   if (umem + length > umem_end)
1122     err("warning: uppermem @ %08x overflows by %d bytes\n",
1123         offset, umem + length - umem_end);
1124
1125   dbg("upper mem @ %08x %x = %p\n", offset, length, umem);
1126   return (long)umem;
1127 }
1128
1129 long emu_do_mmap(unsigned int length, int prot, int flags, int fd,
1130   unsigned int offset)
1131 {
1132   if (fd == FAKEDEV_MEM)
1133     return emu_mmap_dev(length, prot, flags, offset);
1134
1135   if (fd == FAKEDEV_FB0)
1136     return emu_mmap_dev(length, prot, flags, offset + 0x03101000);
1137
1138   if (fd == FAKEDEV_FB1)
1139     return emu_mmap_dev(length, prot, flags, offset + 0x03381000);
1140
1141   err("bad/ni mmap(?, %d, %x, %x, %d, %08x)\n", length, prot, flags, fd, offset);
1142   return -EINVAL;
1143 }
1144
1145 long emu_do_munmap(void *addr, unsigned int length)
1146 {
1147   u8 *p = addr;
1148
1149   // don't allow to unmap upper mem
1150   if ((u8 *)mmsp2.umem <= p && p < (u8 *)mmsp2.umem + 0x2000000) {
1151     dbg("ignoring munmap: %p %x\n", addr, length);
1152     return 0;
1153   }
1154
1155   return -EAGAIN;
1156 }
1157
1158 static void emu_sound_open(int fd)
1159 {
1160 #ifdef PND
1161   int ret, frag;
1162
1163   // set default buffer size to 16 * 1K
1164   frag = (16<<16) | 10; // 16K
1165   ret = g_ioctl_raw(fd, SNDCTL_DSP_SETFRAGMENT, &frag);
1166   if (ret != 0)
1167     err("snd ioctl SETFRAGMENT %08x: %d\n", frag, ret);
1168 #endif
1169 }
1170
1171 static long emu_sound_ioctl(int fd, int request, void *argp)
1172 {
1173   int *arg = argp;
1174
1175 #if 0
1176   dbg("snd ioctl(%d, %08x, %p)", fd, request, argp);
1177   if (arg != NULL)
1178     dbg_c(" [%d]", *arg);
1179   dbg_c("\n");
1180 #endif
1181
1182   /* People set strange frag settings on GP2X, which even manage
1183    * to break audio on pandora (causes writes to fail).
1184    * Catch this and set to something that works. */
1185   switch(request) {
1186     case SNDCTL_DSP_SETFRAGMENT: {
1187       int bsize, frag, frag_cnt;
1188       long ret;
1189
1190       if (arg == NULL)
1191         break;
1192
1193       frag = *arg & 0xffff;
1194       frag_cnt = *arg >> 16;
1195       bsize = frag_cnt << frag;
1196       if (frag < 10 || bsize < 4096*4 || bsize > 4096*4*2) {
1197         /*
1198          * ~4ms. gpSP wants small buffers or else it stutters
1199          * because of it's audio thread sync stuff
1200          * XXX: hardcoding, as low samplerates will result in small fragment size,
1201          * which itself causes ALSA stall and hangs the program.
1202          * Also some apps change samplerate without reopening /dev/dsp,
1203          * which causes ALSA to reject SNDCTL_DSP_SETFRAGMENT.
1204          */
1205         bsize = 44100 / 250 * 4;
1206
1207         for (frag = 0; bsize; bsize >>= 1, frag++)
1208           ;
1209
1210         frag_cnt = 16;
1211       }
1212
1213       frag |= frag_cnt << 16;
1214       ret = g_ioctl_raw(fd, SNDCTL_DSP_SETFRAGMENT, &frag);
1215       if (ret != 0)
1216         err("snd ioctl SETFRAGMENT %08x: %ld\n", frag, ret);
1217       // indicate success even if we fail (because of ALSA mostly),
1218       // things like MikMod will bail out otherwise.
1219       return 0;
1220     }
1221     case SNDCTL_DSP_SYNC:
1222       // Franxis tends to use sync/write loops, bad idea under ALSA
1223       return 0;
1224     default:
1225       break;
1226   }
1227
1228   return g_ioctl_raw(fd, request, argp);
1229 }
1230
1231 long emu_do_ioctl(int fd, int request, void *argp)
1232 {
1233   if (fd == emu_interesting_fds[IFD_SOUND].fd)
1234     return emu_sound_ioctl(fd, request, argp);
1235
1236   switch (fd) {
1237   /* *********************** */
1238   case FAKEDEV_FB0:
1239   case FAKEDEV_FB1:
1240     if (argp == NULL)
1241       goto fail;
1242
1243     switch (request) {
1244       case FBIOGET_FSCREENINFO: {
1245         struct fb_fix_screeninfo *fix = argp;
1246
1247         memset(fix, 0, sizeof(*fix));
1248         strcpy(fix->id, "mmsp2_RGB0");
1249         fix->type         = FB_TYPE_PACKED_PIXELS;
1250         fix->accel        = FB_ACCEL_NONE;
1251         fix->visual       = FB_VISUAL_TRUECOLOR;
1252         fix->line_length  = 320*2;
1253         fix->smem_start   = (fd == FAKEDEV_FB0) ? 0x03101000 : 0x03381000;
1254         fix->smem_len     = 320*240*2;
1255         return 0;
1256       }
1257       case FBIOGET_VSCREENINFO: {
1258         struct fb_var_screeninfo *var = argp;
1259         static const struct fb_bitfield fbb_red   = { offset: 11, length: 5, };
1260         static const struct fb_bitfield fbb_green = { offset:  5, length: 6, };
1261         static const struct fb_bitfield fbb_blue  = { offset:  0, length: 5, };
1262
1263         memset(var, 0, sizeof(*var));
1264         var->activate     = FB_ACTIVATE_NOW;
1265         var->xres         =
1266         var->xres_virtual = 320;
1267         var->yres         =
1268         var->yres_virtual = 240;
1269         var->width        =
1270         var->height       = -1;
1271         var->vmode        = FB_VMODE_NONINTERLACED;
1272         var->bits_per_pixel = 16;
1273         var->red          = fbb_red;
1274         var->green        = fbb_green;
1275         var->blue         = fbb_blue;
1276         return 0;
1277       }
1278       case FBIOPUT_VSCREENINFO: {
1279         struct fb_var_screeninfo *var = argp;
1280         dbg(" put vscreen: %dx%d@%d\n", var->xres, var->yres, var->bits_per_pixel);
1281         if (var->xres != 320 || var->yres != 240 || var->bits_per_pixel != 16)
1282           return -1;
1283         return 0;
1284       }
1285     }
1286
1287   /* *********************** */
1288   case FAKEDEV_TTY0:
1289     // fake tty0 to make GPH SDL happy
1290     if (request == 0x4b46) // KDGKBENT
1291       return -1;
1292     return 0;
1293   }
1294
1295 fail:
1296   err("bad/ni ioctl(%d, %08x, %p)\n", fd, request, argp);
1297   return -EINVAL;
1298 }
1299
1300 static const char wm97xx_p[] =
1301   "5507 0 -831476 0 -4218 16450692 65536"; // from 4.0 fw
1302
1303 long emu_do_read(int fd, void *buf, int count)
1304 {
1305   int ret, pressed = 0, x, y;
1306   struct {
1307     u16 pressure, x, y;
1308   } wm97xx;
1309
1310   if (count < 0) {
1311     err("read(%d, %d)\n", fd, count);
1312     return -EINVAL;
1313   }
1314
1315   switch (fd) {
1316   case FAKEDEV_GPIO:
1317     mmsp2.btn_state = host_read_btns();
1318
1319     if (count > 4)
1320       count = 4;
1321     memcpy(buf, &mmsp2.btn_state, count);
1322     break;
1323   case FAKEDEV_WM97XX:
1324     ret = host_read_ts(&pressed, &x, &y);
1325     if (ret == 0 && pressed) {
1326       wm97xx.pressure = 0x8001; // TODO: check the real thing
1327       wm97xx.x =        x * 3750 / 1024 + 200;
1328       wm97xx.y = 3750 - y * 3750 / 1024 + 200;
1329     }
1330     else {
1331       wm97xx.pressure = 0;
1332       wm97xx.x = wm97xx.y = 200;
1333     }
1334
1335     if (count > sizeof(wm97xx))
1336       count = sizeof(wm97xx);
1337     memcpy(buf, &wm97xx, count);
1338     break;
1339   case FAKEDEV_WM97XX_P:
1340     if (count < sizeof(wm97xx_p))
1341       err("incomplete pointercal read\n");
1342     strncpy(buf, wm97xx_p, count);
1343     break;
1344   default:
1345     dbg("read(%d, %d)\n", fd, count);
1346     return -EINVAL;
1347   }
1348   return count;
1349 }
1350
1351 struct dev_fd_t emu_interesting_fds[] = {
1352   [IFD_SOUND] = { "/dev/dsp", -1, emu_sound_open },
1353   { NULL, 0, NULL },
1354 };
1355
1356 static const struct {
1357   const char *from;
1358   const char *to;
1359 } path_map[] = {
1360   { "/mnt/tmp", "./tmp" },
1361   { "/mnt/sd", "./mntsd" },
1362 };
1363
1364 const char *emu_wrap_path(const char *path)
1365 {
1366   char *buff, *p;
1367   size_t size;
1368   int i, len;
1369   long ret;
1370
1371   // do only path mapping for now
1372   for (i = 0; i < ARRAY_SIZE(path_map); i++) {
1373     p = strstr(path, path_map[i].from);
1374     if (p != NULL) {
1375       size = strlen(path) + strlen(path_map[i].to) + 1;
1376       buff = malloc(size);
1377       if (buff == NULL)
1378         break;
1379       len = p - path;
1380       strncpy(buff, path, len);
1381       snprintf(buff + len, size - len, "%s%s", path_map[i].to,
1382         path + len + strlen(path_map[i].from));
1383       dbg("mapped path \"%s\" -> \"%s\"\n", path, buff);
1384
1385       ret = g_mkdir_raw(path_map[i].to, 0666);
1386       if (ret != 0 && ret != -EEXIST)
1387         err("mkdir(%s): %ld\n", path_map[i].to, ret);
1388
1389       return buff;
1390     }
1391   }
1392
1393   return path;
1394 }
1395
1396 void emu_wrap_path_free(const char *w_path, const char *old_path)
1397 {
1398   if (w_path != old_path)
1399     free((void *)w_path);
1400 }
1401
1402 void *emu_do_fopen(const char *path, const char *mode)
1403 {
1404   const char *w_path;
1405   FILE *ret;
1406
1407   if (strcmp(path, "/etc/pointercal") == 0) {
1408     // use local pontercal, not host's
1409     ret = fopen("pointercal", mode);
1410     if (ret == NULL) {
1411       ret = fopen("pointercal", "w");
1412       if (ret != NULL) {
1413         fwrite(wm97xx_p, 1, sizeof(wm97xx_p), ret);
1414         fclose(ret);
1415       }
1416       ret = fopen("pointercal", mode);
1417     }
1418   }
1419   else {
1420     w_path = emu_wrap_path(path);
1421     ret = fopen(w_path, mode);
1422     emu_wrap_path_free(w_path, path);
1423   }
1424
1425   return ret;
1426 }
1427
1428 // FIXME: threads..
1429 int emu_do_system(const char *command)
1430 {
1431   static char tmp_path[512];
1432   int need_ginge = 0;
1433   const char *p2;
1434   char *p;
1435   int ret;
1436
1437   if (command == NULL)
1438     return -1;
1439
1440   for (p2 = command; *p2 && isspace(*p2); p2++)
1441     ;
1442
1443   if (*p2 == '.') // relative path?
1444     need_ginge = 1;
1445   else if (*p2 == '/' && strncmp(p2, "/bin", 4) && strncmp(p2, "/lib", 4)
1446            && strncmp(p2, "/sbin", 4) && strncmp(p2, "/usr", 4))
1447     // absolute path, but not a system command
1448     need_ginge = 1;
1449
1450   p2 = emu_wrap_path(command);
1451   if (need_ginge) {
1452     make_local_path(tmp_path, sizeof(tmp_path), "ginge_prep");
1453     p = tmp_path + strlen(tmp_path);
1454
1455     snprintf(p, sizeof(tmp_path) - (p - tmp_path), " --nomenu %s", p2);
1456   }
1457   else
1458     snprintf(tmp_path, sizeof(tmp_path), "%s", p2);
1459   emu_wrap_path_free(p2, command);
1460
1461   dbg("system: \"%s\"\n", tmp_path);
1462
1463   // the app might want the screen too..
1464   fb_thread_pause();
1465   ret = system(tmp_path);
1466   fb_thread_resume();
1467   return ret;
1468 }
1469
1470 long emu_do_execve(const char *filename, char * const argv[],
1471                    char * const envp[])
1472 {
1473   const char **new_argv;
1474   char *prep_path;
1475   int i, argc;
1476   long ret;
1477
1478   if (filename == NULL)
1479     return -1;
1480
1481   if (strstr(filename, "gp2xmenu") != NULL)
1482     host_forced_exit(0);
1483
1484   for (i = 0; argv[i] != NULL; i++)
1485     ;
1486   argc = i + 1;
1487
1488   new_argv = calloc(argc + 2, sizeof(new_argv[0]));
1489   if (new_argv == NULL)
1490     return -1;
1491
1492   prep_path = malloc(512);
1493   if (prep_path == NULL)
1494     return -1;
1495
1496   make_local_path(prep_path, 512, "ginge_prep");
1497   new_argv[0] = prep_path;
1498   new_argv[1] = "--nomenu";
1499   new_argv[2] = emu_wrap_path(filename);
1500
1501   if (argv[0] != NULL)
1502     for (i = 1; argv[i] != NULL; i++)
1503       new_argv[i + 2] = argv[i];
1504
1505   dbg("execve \"%s\" %s \"%s\"\n", new_argv[0], new_argv[1], new_argv[2]);
1506   ret = execve(new_argv[0], (char **)new_argv, envp);
1507   err("execve(%s): %ld\n", new_argv[0], ret);
1508   return ret;
1509 }
1510
1511 // vim:shiftwidth=2:expandtab