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