ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.14
Committed: 2003-11-10T16:05:52Z (21 years ago) by gbeauche
Branch: MAIN
Changes since 1.13: +24 -1 lines
Log Message:
Merge Set_pthread_attr() from Basilisk II.

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * main_unix.cpp - Emulation core, Unix implementation
3     *
4     * SheepShaver (C) 1997-2002 Christian Bauer and Marc Hellwig
5     *
6     * This program is free software; you can redistribute it and/or modify
7     * it under the terms of the GNU General Public License as published by
8     * the Free Software Foundation; either version 2 of the License, or
9     * (at your option) any later version.
10     *
11     * This program is distributed in the hope that it will be useful,
12     * but WITHOUT ANY WARRANTY; without even the implied warranty of
13     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14     * GNU General Public License for more details.
15     *
16     * You should have received a copy of the GNU General Public License
17     * along with this program; if not, write to the Free Software
18     * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19     */
20    
21     /*
22     * NOTES:
23     *
24     * See main_beos.cpp for a description of the three operating modes.
25     *
26     * In addition to that, we have to handle the fact that the MacOS ABI
27     * is slightly different from the SysV ABI used by Linux:
28     * - Stack frames are different (e.g. LR is stored in 8(r1) under
29     * MacOS, but in 4(r1) under Linux)
30     * - There is no TOC under Linux; r2 is free for the user
31     * - r13 is used as a small data pointer under Linux (but appearently
32     * it is not used this way? To be sure, we specify -msdata=none
33     * in the Makefile)
34     * - As there is no TOC, there are also no TVECTs under Linux;
35     * function pointers point directly to the function code
36     * The Execute*() functions have to account for this. Additionally, we
37     * cannot simply call MacOS functions by getting their TVECT and jumping
38     * to it. Such calls are done via the call_macos*() functions in
39     * asm_linux.S that create a MacOS stack frame, load the TOC pointer
40     * and put the arguments into the right registers.
41     *
42     * As on the BeOS, we have to specify an alternate signal stack because
43     * interrupts (and, under Linux, Low Memory accesses) may occur when r1
44     * is pointing to the Kernel Data or to Low Memory. There is one
45     * problem, however, due to the alternate signal stack being global to
46     * all signal handlers. Consider the following scenario:
47     * - The main thread is executing some native PPC MacOS code in
48     * MODE_NATIVE, running on the MacOS stack (somewhere in the Mac RAM).
49     * - A SIGUSR2 interrupt occurs. The kernel switches to the signal
50     * stack and starts executing the SIGUSR2 signal handler.
51     * - The signal handler sees the MODE_NATIVE and calls ppc_interrupt()
52     * to handle a native interrupt.
53     * - ppc_interrupt() sets r1 to point to the Kernel Data and jumps to
54     * the nanokernel.
55     * - The nanokernel accesses a Low Memory global (most likely one of
56     * the XLMs), a SIGSEGV occurs.
57     * - The kernel sees that r1 does not point to the signal stack and
58     * switches to the signal stack again, thus overwriting the data that
59     * the SIGUSR2 handler put there.
60     * The same problem arises when calling ExecutePPC() inside the MODE_EMUL_OP
61     * interrupt handler.
62     *
63     * The solution is to set the signal stack to a second, "extra" stack
64     * inside the SIGUSR2 handler before entering the Nanokernel or calling
65     * ExecutePPC (or any function that might cause a mode switch). The signal
66     * stack is restored before exiting the SIGUSR2 handler.
67     *
68     * TODO:
69     * check if SIGSEGV handler works for all registers (including FP!)
70     */
71    
72     #include <unistd.h>
73     #include <fcntl.h>
74     #include <time.h>
75     #include <errno.h>
76     #include <stdio.h>
77     #include <stdlib.h>
78     #include <string.h>
79     #include <pthread.h>
80     #include <sys/mman.h>
81     #include <sys/ipc.h>
82     #include <sys/shm.h>
83     #include <signal.h>
84    
85     #include "sysdeps.h"
86     #include "main.h"
87     #include "version.h"
88     #include "prefs.h"
89     #include "prefs_editor.h"
90     #include "cpu_emulation.h"
91     #include "emul_op.h"
92     #include "xlowmem.h"
93     #include "xpram.h"
94     #include "timer.h"
95     #include "adb.h"
96     #include "sony.h"
97     #include "disk.h"
98     #include "cdrom.h"
99     #include "scsi.h"
100     #include "video.h"
101     #include "audio.h"
102     #include "ether.h"
103     #include "serial.h"
104     #include "clip.h"
105     #include "extfs.h"
106     #include "sys.h"
107     #include "macos_util.h"
108     #include "rom_patches.h"
109     #include "user_strings.h"
110 gbeauche 1.4 #include "vm_alloc.h"
111 gbeauche 1.5 #include "sigsegv.h"
112 cebix 1.1
113     #define DEBUG 0
114     #include "debug.h"
115    
116    
117     #include <X11/Xlib.h>
118    
119     #ifdef ENABLE_GTK
120     #include <gtk/gtk.h>
121     #endif
122    
123     #ifdef ENABLE_XF86_DGA
124     #include <X11/Xlib.h>
125     #include <X11/Xutil.h>
126     #include <X11/extensions/xf86dga.h>
127     #endif
128    
129     #ifdef ENABLE_MON
130     #include "mon.h"
131     #endif
132    
133    
134     // Enable Execute68k() safety checks?
135     #define SAFE_EXEC_68K 0
136    
137     // Interrupts in EMUL_OP mode?
138     #define INTERRUPTS_IN_EMUL_OP_MODE 1
139    
140     // Interrupts in native mode?
141     #define INTERRUPTS_IN_NATIVE_MODE 1
142    
143    
144     // Constants
145     const char ROM_FILE_NAME[] = "ROM";
146     const char ROM_FILE_NAME2[] = "Mac OS ROM";
147    
148 gbeauche 1.8 const uint32 RAM_BASE = 0x20000000; // Base address of RAM
149 cebix 1.1 const uint32 SIG_STACK_SIZE = 0x10000; // Size of signal stack
150    
151    
152     #if !EMULATED_PPC
153     // Structure in which registers are saved in a signal handler;
154     // sigcontext->regs points to it
155     // (see arch/ppc/kernel/signal.c)
156     typedef struct {
157     uint32 u[4];
158     } __attribute((aligned(16))) vector128;
159     #include <linux/elf.h>
160    
161     struct sigregs {
162     elf_gregset_t gp_regs; // Identical to pt_regs
163     double fp_regs[ELF_NFPREG]; // f0..f31 and fpsrc
164     //more (uninteresting) stuff following here
165     };
166     #endif
167    
168    
169     // Global variables (exported)
170     #if !EMULATED_PPC
171     void *TOC; // Small data pointer (r13)
172     #endif
173     uint32 RAMBase; // Base address of Mac RAM
174     uint32 RAMSize; // Size of Mac RAM
175 gbeauche 1.8 uint32 SheepStack1Base; // SheepShaver first alternate stack base
176     uint32 SheepStack2Base; // SheepShaver second alternate stack base
177     uint32 SheepThunksBase; // SheepShaver thunks base
178 cebix 1.1 uint32 KernelDataAddr; // Address of Kernel Data
179     uint32 BootGlobsAddr; // Address of BootGlobs structure at top of Mac RAM
180     uint32 PVR; // Theoretical PVR
181     int64 CPUClockSpeed; // Processor clock speed (Hz)
182     int64 BusClockSpeed; // Bus clock speed (Hz)
183    
184    
185     // Global variables
186 gbeauche 1.11 char *x_display_name = NULL; // X11 display name
187 cebix 1.1 Display *x_display = NULL; // X11 display handle
188    
189     static int zero_fd = 0; // FD of /dev/zero
190 gbeauche 1.8 static bool sheep_area_mapped = false; // Flag: SheepShaver data area mmap()ed
191 cebix 1.1 static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
192     static int kernel_area = -1; // SHM ID of Kernel Data area
193     static bool rom_area_mapped = false; // Flag: Mac ROM mmap()ped
194     static bool ram_area_mapped = false; // Flag: Mac RAM mmap()ped
195     static KernelData *kernel_data; // Pointer to Kernel Data
196     static EmulatorData *emulator_data;
197    
198     static uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes
199    
200     static bool nvram_thread_active = false; // Flag: NVRAM watchdog installed
201     static pthread_t nvram_thread; // NVRAM watchdog
202     static bool tick_thread_active = false; // Flag: MacOS thread installed
203     static pthread_t tick_thread; // 60Hz thread
204     static pthread_t emul_thread; // MacOS thread
205    
206     static bool ready_for_signals = false; // Handler installed, signals can be sent
207     static int64 num_segv = 0; // Number of handled SEGV signals
208    
209 gbeauche 1.6 static struct sigaction sigusr2_action; // Interrupt signal (of emulator thread)
210 cebix 1.1 #if !EMULATED_PPC
211     static struct sigaction sigsegv_action; // Data access exception signal (of emulator thread)
212     static struct sigaction sigill_action; // Illegal instruction signal (of emulator thread)
213     static void *sig_stack = NULL; // Stack for signal handlers
214     static void *extra_stack = NULL; // Stack for SIGSEGV inside interrupt handler
215     static bool emul_thread_fatal = false; // Flag: MacOS thread crashed, tick thread shall dump debug output
216     static sigregs sigsegv_regs; // Register dump when crashed
217     #endif
218    
219    
220     // Prototypes
221     static void Quit(void);
222     static void *emul_func(void *arg);
223     static void *nvram_func(void *arg);
224     static void *tick_func(void *arg);
225 gbeauche 1.8 #if EMULATED_PPC
226     static void sigusr2_handler(int sig);
227 gbeauche 1.13 extern void emul_ppc(uint32 start);
228     extern void init_emul_ppc(void);
229     extern void exit_emul_ppc(void);
230 gbeauche 1.8 #else
231 gbeauche 1.6 static void sigusr2_handler(int sig, sigcontext_struct *sc);
232 cebix 1.1 static void sigsegv_handler(int sig, sigcontext_struct *sc);
233     static void sigill_handler(int sig, sigcontext_struct *sc);
234     #endif
235    
236    
237     // From asm_linux.S
238 gbeauche 1.12 #if !EMULATED_PPC
239 cebix 1.1 extern "C" void *get_toc(void);
240     extern "C" void *get_sp(void);
241     extern "C" void flush_icache_range(void *start, void *end);
242     extern "C" void jump_to_rom(uint32 entry, uint32 context);
243     extern "C" void quit_emulator(void);
244     extern "C" void execute_68k(uint32 pc, M68kRegisters *r);
245     extern "C" void ppc_interrupt(uint32 entry, uint32 kernel_data);
246     extern "C" int atomic_add(int *var, int v);
247     extern "C" int atomic_and(int *var, int v);
248     extern "C" int atomic_or(int *var, int v);
249     extern void paranoia_check(void);
250 gbeauche 1.12 #endif
251    
252    
253     #if EMULATED_PPC
254     /*
255     * Atomic operations
256     */
257    
258     #if HAVE_SPINLOCKS
259     static spinlock_t atomic_ops_lock = SPIN_LOCK_UNLOCKED;
260     #else
261     #define spin_lock(LOCK)
262     #define spin_unlock(LOCK)
263     #endif
264    
265     int atomic_add(int *var, int v)
266     {
267     spin_lock(&atomic_ops_lock);
268     int ret = *var;
269     *var += v;
270     spin_unlock(&atomic_ops_lock);
271     return ret;
272     }
273    
274     int atomic_and(int *var, int v)
275     {
276     spin_lock(&atomic_ops_lock);
277     int ret = *var;
278     *var &= v;
279     spin_unlock(&atomic_ops_lock);
280     return ret;
281     }
282    
283     int atomic_or(int *var, int v)
284     {
285     spin_lock(&atomic_ops_lock);
286     int ret = *var;
287     *var |= v;
288     spin_unlock(&atomic_ops_lock);
289     return ret;
290     }
291 cebix 1.1 #endif
292    
293    
294     /*
295     * Main program
296     */
297    
298     static void usage(const char *prg_name)
299     {
300     printf("Usage: %s [OPTION...]\n", prg_name);
301     printf("\nUnix options:\n");
302     printf(" --display STRING\n X display to use\n");
303     PrefsPrintUsage();
304     exit(0);
305     }
306    
307     int main(int argc, char **argv)
308     {
309     char str[256];
310     uint32 *boot_globs;
311     int16 i16;
312     int rom_fd;
313     FILE *proc_file;
314     const char *rom_path;
315     uint32 rom_size, actual;
316     uint8 *rom_tmp;
317     time_t now, expire;
318    
319     // Initialize variables
320     RAMBase = 0;
321     tzset();
322    
323     // Print some info
324     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
325     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
326    
327     #if !EMULATED_PPC
328     // Get TOC pointer
329     TOC = get_toc();
330     #endif
331    
332     #ifdef ENABLE_GTK
333     // Init GTK
334     gtk_set_locale();
335     gtk_init(&argc, &argv);
336     #endif
337    
338     // Read preferences
339     PrefsInit(argc, argv);
340    
341     // Parse command line arguments
342     for (int i=1; i<argc; i++) {
343     if (strcmp(argv[i], "--help") == 0) {
344     usage(argv[0]);
345     } else if (strcmp(argv[i], "--display") == 0) {
346     i++;
347     if (i < argc)
348     x_display_name = strdup(argv[i]);
349     } else if (argv[i][0] == '-') {
350     fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
351     usage(argv[0]);
352     }
353     }
354    
355     // Open display
356     x_display = XOpenDisplay(x_display_name);
357     if (x_display == NULL) {
358     char str[256];
359     sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
360     ErrorAlert(str);
361     goto quit;
362     }
363    
364     #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
365     // Fork out, so we can return from fullscreen mode when things get ugly
366     XF86DGAForkApp(DefaultScreen(x_display));
367     #endif
368    
369     #ifdef ENABLE_MON
370     // Initialize mon
371     mon_init();
372     #endif
373    
374     // Get system info
375     PVR = 0x00040000; // Default: 604
376     CPUClockSpeed = 100000000; // Default: 100MHz
377     BusClockSpeed = 100000000; // Default: 100MHz
378     #if !EMULATED_PPC
379     proc_file = fopen("/proc/cpuinfo", "r");
380     if (proc_file) {
381     char line[256];
382     while(fgets(line, 255, proc_file)) {
383     // Read line
384     int len = strlen(line);
385     if (len == 0)
386     continue;
387     line[len-1] = 0;
388    
389     // Parse line
390     int i;
391     char value[256];
392     if (sscanf(line, "cpu : %s", value) == 1) {
393     if (strcmp(value, "601") == 0)
394     PVR = 0x00010000;
395     else if (strcmp(value, "603") == 0)
396     PVR = 0x00030000;
397     else if (strcmp(value, "604") == 0)
398     PVR = 0x00040000;
399     else if (strcmp(value, "603e") == 0)
400     PVR = 0x00060000;
401     else if (strcmp(value, "603ev") == 0)
402     PVR = 0x00070000;
403     else if (strcmp(value, "604e") == 0)
404     PVR = 0x00090000;
405     else if (strcmp(value, "604ev5") == 0)
406     PVR = 0x000a0000;
407     else if (strcmp(value, "750") == 0)
408     PVR = 0x00080000;
409     else if (strcmp(value, "821") == 0)
410     PVR = 0x00320000;
411     else if (strcmp(value, "860") == 0)
412     PVR = 0x00500000;
413     else
414     printf("WARNING: Unknown CPU type '%s', assuming 604\n", value);
415     }
416     if (sscanf(line, "clock : %dMHz", &i) == 1)
417     CPUClockSpeed = BusClockSpeed = i * 1000000;
418     }
419     fclose(proc_file);
420     } else {
421     sprintf(str, GetString(STR_PROC_CPUINFO_WARN), strerror(errno));
422     WarningAlert(str);
423     }
424     #endif
425     D(bug("PVR: %08x (assumed)\n", PVR));
426    
427     // Init system routines
428     SysInit();
429    
430     // Show preferences editor
431     if (!PrefsFindBool("nogui"))
432     if (!PrefsEditor())
433     goto quit;
434    
435     #if !EMULATED_PPC
436     // Check some things
437     paranoia_check();
438     #endif
439    
440     // Open /dev/zero
441     zero_fd = open("/dev/zero", O_RDWR);
442     if (zero_fd < 0) {
443     sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
444     ErrorAlert(str);
445     goto quit;
446     }
447    
448     // Create Low Memory area (0x0000..0x3000)
449 gbeauche 1.4 if (vm_acquire_fixed((char *)0, 0x3000) < 0) {
450 cebix 1.1 sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
451     ErrorAlert(str);
452     goto quit;
453     }
454     lm_area_mapped = true;
455    
456     // Create areas for Kernel Data
457     kernel_area = shmget(IPC_PRIVATE, KERNEL_AREA_SIZE, 0600);
458     if (kernel_area == -1) {
459     sprintf(str, GetString(STR_KD_SHMGET_ERR), strerror(errno));
460     ErrorAlert(str);
461     goto quit;
462     }
463     if (shmat(kernel_area, (void *)KERNEL_DATA_BASE, 0) < 0) {
464     sprintf(str, GetString(STR_KD_SHMAT_ERR), strerror(errno));
465     ErrorAlert(str);
466     goto quit;
467     }
468     if (shmat(kernel_area, (void *)KERNEL_DATA2_BASE, 0) < 0) {
469     sprintf(str, GetString(STR_KD2_SHMAT_ERR), strerror(errno));
470     ErrorAlert(str);
471     goto quit;
472     }
473     kernel_data = (KernelData *)0x68ffe000;
474     emulator_data = &kernel_data->ed;
475     KernelDataAddr = (uint32)kernel_data;
476     D(bug("Kernel Data at %p, Emulator Data at %p\n", kernel_data, emulator_data));
477    
478 gbeauche 1.8 // Create area for SheepShaver data
479     if (vm_acquire_fixed((char *)SHEEP_BASE, SHEEP_SIZE) < 0) {
480     sprintf(str, GetString(STR_SHEEP_MEM_MMAP_ERR), strerror(errno));
481     ErrorAlert(str);
482     goto quit;
483     }
484     SheepStack1Base = SHEEP_BASE + 0x10000;
485     SheepStack2Base = SheepStack1Base + 0x10000;
486     SheepThunksBase = SheepStack2Base + 0x1000;
487     sheep_area_mapped = true;
488    
489 cebix 1.1 // Create area for Mac ROM
490 gbeauche 1.4 if (vm_acquire_fixed((char *)ROM_BASE, ROM_AREA_SIZE) < 0) {
491 cebix 1.1 sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
492     ErrorAlert(str);
493     goto quit;
494     }
495 gbeauche 1.6 #if !EMULATED_PPC || defined(__powerpc__)
496 gbeauche 1.4 if (vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
497     sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
498     ErrorAlert(str);
499     goto quit;
500     }
501     #endif
502 cebix 1.1 rom_area_mapped = true;
503     D(bug("ROM area at %08x\n", ROM_BASE));
504    
505     // Create area for Mac RAM
506     RAMSize = PrefsFindInt32("ramsize");
507     if (RAMSize < 8*1024*1024) {
508     WarningAlert(GetString(STR_SMALL_RAM_WARN));
509     RAMSize = 8*1024*1024;
510     }
511    
512 gbeauche 1.8 if (vm_acquire_fixed((char *)RAM_BASE, RAMSize) < 0) {
513 cebix 1.1 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
514     ErrorAlert(str);
515     goto quit;
516     }
517 gbeauche 1.4 #if !EMULATED_PPC
518 gbeauche 1.8 if (vm_protect((char *)RAM_BASE, RAMSize, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
519 gbeauche 1.4 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
520     ErrorAlert(str);
521     goto quit;
522     }
523     #endif
524 gbeauche 1.8 RAMBase = RAM_BASE;
525 cebix 1.1 ram_area_mapped = true;
526     D(bug("RAM area at %08x\n", RAMBase));
527    
528     if (RAMBase > ROM_BASE) {
529     ErrorAlert(GetString(STR_RAM_HIGHER_THAN_ROM_ERR));
530     goto quit;
531     }
532    
533     // Load Mac ROM
534     rom_path = PrefsFindString("rom");
535     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
536     if (rom_fd < 0) {
537     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME2, O_RDONLY);
538     if (rom_fd < 0) {
539     ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
540     goto quit;
541     }
542     }
543     printf(GetString(STR_READING_ROM_FILE));
544     rom_size = lseek(rom_fd, 0, SEEK_END);
545     lseek(rom_fd, 0, SEEK_SET);
546     rom_tmp = new uint8[ROM_SIZE];
547     actual = read(rom_fd, (void *)rom_tmp, ROM_SIZE);
548     close(rom_fd);
549 gbeauche 1.3
550     // Decode Mac ROM
551     if (!DecodeROM(rom_tmp, actual)) {
552     if (rom_size != 4*1024*1024) {
553 cebix 1.1 ErrorAlert(GetString(STR_ROM_SIZE_ERR));
554     goto quit;
555     } else {
556     ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
557     goto quit;
558     }
559     }
560 gbeauche 1.3 delete[] rom_tmp;
561 cebix 1.1
562     // Load NVRAM
563     XPRAMInit();
564    
565     // Set boot volume
566 cebix 1.10 i16 = PrefsFindInt32("bootdrive");
567 cebix 1.1 XPRAM[0x1378] = i16 >> 8;
568     XPRAM[0x1379] = i16 & 0xff;
569 cebix 1.10 i16 = PrefsFindInt32("bootdriver");
570 cebix 1.1 XPRAM[0x137a] = i16 >> 8;
571     XPRAM[0x137b] = i16 & 0xff;
572    
573     // Create BootGlobs at top of Mac memory
574     memset((void *)(RAMBase + RAMSize - 4096), 0, 4096);
575     BootGlobsAddr = RAMBase + RAMSize - 0x1c;
576     boot_globs = (uint32 *)BootGlobsAddr;
577     boot_globs[-5] = htonl(RAMBase + RAMSize); // MemTop
578     boot_globs[0] = htonl(RAMBase); // First RAM bank
579     boot_globs[1] = htonl(RAMSize);
580     boot_globs[2] = htonl((uint32)-1); // End of bank table
581    
582     // Init drivers
583     SonyInit();
584     DiskInit();
585     CDROMInit();
586     SCSIInit();
587    
588     // Init external file system
589     ExtFSInit();
590    
591     // Init audio
592     AudioInit();
593    
594     // Init network
595     EtherInit();
596    
597     // Init serial ports
598     SerialInit();
599    
600     // Init Time Manager
601     TimerInit();
602    
603     // Init clipboard
604     ClipInit();
605    
606     // Init video
607     if (!VideoInit())
608     goto quit;
609    
610     // Install ROM patches
611     if (!PatchROM()) {
612     ErrorAlert(GetString(STR_UNSUPPORTED_ROM_TYPE_ERR));
613     goto quit;
614     }
615    
616     // Clear caches (as we loaded and patched code) and write protect ROM
617     #if !EMULATED_PPC
618     MakeExecutable(0, (void *)ROM_BASE, ROM_AREA_SIZE);
619     #endif
620 gbeauche 1.4 vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_EXECUTE);
621 cebix 1.1
622     // Initialize Kernel Data
623     memset(kernel_data, 0, sizeof(KernelData));
624     if (ROMType == ROMTYPE_NEWWORLD) {
625     static uint32 of_dev_tree[4] = {0, 0, 0, 0};
626     static uint8 vector_lookup_tbl[128];
627     static uint8 vector_mask_tbl[64];
628     memset((uint8 *)kernel_data + 0xb80, 0x3d, 0x80);
629     memset(vector_lookup_tbl, 0, 128);
630     memset(vector_mask_tbl, 0, 64);
631     kernel_data->v[0xb80 >> 2] = htonl(ROM_BASE);
632     kernel_data->v[0xb84 >> 2] = htonl((uint32)of_dev_tree); // OF device tree base
633     kernel_data->v[0xb90 >> 2] = htonl((uint32)vector_lookup_tbl);
634     kernel_data->v[0xb94 >> 2] = htonl((uint32)vector_mask_tbl);
635     kernel_data->v[0xb98 >> 2] = htonl(ROM_BASE); // OpenPIC base
636     kernel_data->v[0xbb0 >> 2] = htonl(0); // ADB base
637     kernel_data->v[0xc20 >> 2] = htonl(RAMSize);
638     kernel_data->v[0xc24 >> 2] = htonl(RAMSize);
639     kernel_data->v[0xc30 >> 2] = htonl(RAMSize);
640     kernel_data->v[0xc34 >> 2] = htonl(RAMSize);
641     kernel_data->v[0xc38 >> 2] = htonl(0x00010020);
642     kernel_data->v[0xc3c >> 2] = htonl(0x00200001);
643     kernel_data->v[0xc40 >> 2] = htonl(0x00010000);
644     kernel_data->v[0xc50 >> 2] = htonl(RAMBase);
645     kernel_data->v[0xc54 >> 2] = htonl(RAMSize);
646     kernel_data->v[0xf60 >> 2] = htonl(PVR);
647     kernel_data->v[0xf64 >> 2] = htonl(CPUClockSpeed);
648     kernel_data->v[0xf68 >> 2] = htonl(BusClockSpeed);
649     kernel_data->v[0xf6c >> 2] = htonl(CPUClockSpeed);
650     } else {
651     kernel_data->v[0xc80 >> 2] = htonl(RAMSize);
652     kernel_data->v[0xc84 >> 2] = htonl(RAMSize);
653     kernel_data->v[0xc90 >> 2] = htonl(RAMSize);
654     kernel_data->v[0xc94 >> 2] = htonl(RAMSize);
655     kernel_data->v[0xc98 >> 2] = htonl(0x00010020);
656     kernel_data->v[0xc9c >> 2] = htonl(0x00200001);
657     kernel_data->v[0xca0 >> 2] = htonl(0x00010000);
658     kernel_data->v[0xcb0 >> 2] = htonl(RAMBase);
659     kernel_data->v[0xcb4 >> 2] = htonl(RAMSize);
660     kernel_data->v[0xf80 >> 2] = htonl(PVR);
661     kernel_data->v[0xf84 >> 2] = htonl(CPUClockSpeed);
662     kernel_data->v[0xf88 >> 2] = htonl(BusClockSpeed);
663     kernel_data->v[0xf8c >> 2] = htonl(CPUClockSpeed);
664     }
665    
666     // Initialize extra low memory
667     D(bug("Initializing Low Memory...\n"));
668     memset(NULL, 0, 0x3000);
669     WriteMacInt32(XLM_SIGNATURE, FOURCC('B','a','a','h')); // Signature to detect SheepShaver
670     WriteMacInt32(XLM_KERNEL_DATA, (uint32)kernel_data); // For trap replacement routines
671     WriteMacInt32(XLM_PVR, PVR); // Theoretical PVR
672     WriteMacInt32(XLM_BUS_CLOCK, BusClockSpeed); // For DriverServicesLib patch
673     WriteMacInt16(XLM_EXEC_RETURN_OPCODE, M68K_EXEC_RETURN); // For Execute68k() (RTS from the executed 68k code will jump here and end 68k mode)
674 gbeauche 1.6 #if EMULATED_PPC
675     WriteMacInt32(XLM_ETHER_INIT, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_INIT));
676     WriteMacInt32(XLM_ETHER_TERM, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_TERM));
677     WriteMacInt32(XLM_ETHER_OPEN, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_OPEN));
678     WriteMacInt32(XLM_ETHER_CLOSE, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_CLOSE));
679     WriteMacInt32(XLM_ETHER_WPUT, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_WPUT));
680     WriteMacInt32(XLM_ETHER_RSRV, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_RSRV));
681     WriteMacInt32(XLM_VIDEO_DOIO, POWERPC_NATIVE_OP_FUNC(NATIVE_VIDEO_DO_DRIVER_IO));
682     #else
683 cebix 1.1 WriteMacInt32(XLM_TOC, (uint32)TOC); // TOC pointer of emulator
684     WriteMacInt32(XLM_ETHER_INIT, (uint32)InitStreamModule); // DLPI ethernet driver functions
685     WriteMacInt32(XLM_ETHER_TERM, (uint32)TerminateStreamModule);
686     WriteMacInt32(XLM_ETHER_OPEN, (uint32)ether_open);
687     WriteMacInt32(XLM_ETHER_CLOSE, (uint32)ether_close);
688     WriteMacInt32(XLM_ETHER_WPUT, (uint32)ether_wput);
689     WriteMacInt32(XLM_ETHER_RSRV, (uint32)ether_rsrv);
690     WriteMacInt32(XLM_VIDEO_DOIO, (uint32)VideoDoDriverIO);
691     #endif
692     D(bug("Low Memory initialized\n"));
693    
694     // Start 60Hz thread
695     tick_thread_active = (pthread_create(&tick_thread, NULL, tick_func, NULL) == 0);
696     D(bug("Tick thread installed (%ld)\n", tick_thread));
697    
698     // Start NVRAM watchdog thread
699     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
700     nvram_thread_active = (pthread_create(&nvram_thread, NULL, nvram_func, NULL) == 0);
701     D(bug("NVRAM thread installed (%ld)\n", nvram_thread));
702    
703     #if !EMULATED_PPC
704     // Create and install stacks for signal handlers
705     sig_stack = malloc(SIG_STACK_SIZE);
706     D(bug("Signal stack at %p\n", sig_stack));
707     if (sig_stack == NULL) {
708     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
709     goto quit;
710     }
711     extra_stack = malloc(SIG_STACK_SIZE);
712     D(bug("Extra stack at %p\n", extra_stack));
713     if (extra_stack == NULL) {
714     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
715     goto quit;
716     }
717     struct sigaltstack new_stack;
718     new_stack.ss_sp = sig_stack;
719     new_stack.ss_flags = 0;
720     new_stack.ss_size = SIG_STACK_SIZE;
721     if (sigaltstack(&new_stack, NULL) < 0) {
722     sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
723     ErrorAlert(str);
724     goto quit;
725     }
726     #endif
727    
728     #if !EMULATED_PPC
729     // Install SIGSEGV handler
730     sigemptyset(&sigsegv_action.sa_mask); // Block interrupts during SEGV handling
731     sigaddset(&sigsegv_action.sa_mask, SIGUSR2);
732     sigsegv_action.sa_handler = (__sighandler_t)sigsegv_handler;
733     sigsegv_action.sa_flags = SA_ONSTACK;
734     sigsegv_action.sa_restorer = NULL;
735     if (sigaction(SIGSEGV, &sigsegv_action, NULL) < 0) {
736     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
737     ErrorAlert(str);
738     goto quit;
739     }
740    
741     // Install SIGILL handler
742     sigemptyset(&sigill_action.sa_mask); // Block interrupts during ILL handling
743     sigaddset(&sigill_action.sa_mask, SIGUSR2);
744     sigill_action.sa_handler = (__sighandler_t)sigill_handler;
745     sigill_action.sa_flags = SA_ONSTACK;
746     sigill_action.sa_restorer = NULL;
747     if (sigaction(SIGILL, &sigill_action, NULL) < 0) {
748     sprintf(str, GetString(STR_SIGILL_INSTALL_ERR), strerror(errno));
749     ErrorAlert(str);
750     goto quit;
751     }
752 gbeauche 1.6 #endif
753 cebix 1.1
754     // Install interrupt signal handler
755     sigemptyset(&sigusr2_action.sa_mask);
756     sigusr2_action.sa_handler = (__sighandler_t)sigusr2_handler;
757 gbeauche 1.8 sigusr2_action.sa_flags = 0;
758     #if !EMULATED_PPC
759 cebix 1.1 sigusr2_action.sa_flags = SA_ONSTACK | SA_RESTART;
760 gbeauche 1.8 #endif
761 cebix 1.1 sigusr2_action.sa_restorer = NULL;
762     if (sigaction(SIGUSR2, &sigusr2_action, NULL) < 0) {
763     sprintf(str, GetString(STR_SIGUSR2_INSTALL_ERR), strerror(errno));
764     ErrorAlert(str);
765     goto quit;
766     }
767    
768     // Get my thread ID and execute MacOS thread function
769     emul_thread = pthread_self();
770     D(bug("MacOS thread is %ld\n", emul_thread));
771     emul_func(NULL);
772    
773     quit:
774     Quit();
775     return 0;
776     }
777    
778    
779     /*
780     * Cleanup and quit
781     */
782    
783     static void Quit(void)
784     {
785 gbeauche 1.13 #if EMULATED_PPC
786     // Exit PowerPC emulation
787     exit_emul_ppc();
788     #endif
789    
790 cebix 1.1 // Stop 60Hz thread
791     if (tick_thread_active) {
792     pthread_cancel(tick_thread);
793     pthread_join(tick_thread, NULL);
794     }
795    
796     // Stop NVRAM watchdog thread
797     if (nvram_thread_active) {
798     pthread_cancel(nvram_thread);
799     pthread_join(nvram_thread, NULL);
800     }
801    
802     #if !EMULATED_PPC
803     // Uninstall SIGSEGV handler
804     sigemptyset(&sigsegv_action.sa_mask);
805     sigsegv_action.sa_handler = SIG_DFL;
806     sigsegv_action.sa_flags = 0;
807     sigaction(SIGSEGV, &sigsegv_action, NULL);
808    
809     // Uninstall SIGILL handler
810     sigemptyset(&sigill_action.sa_mask);
811     sigill_action.sa_handler = SIG_DFL;
812     sigill_action.sa_flags = 0;
813     sigaction(SIGILL, &sigill_action, NULL);
814     #endif
815    
816     // Save NVRAM
817     XPRAMExit();
818    
819     // Exit clipboard
820     ClipExit();
821    
822     // Exit Time Manager
823     TimerExit();
824    
825     // Exit serial
826     SerialExit();
827    
828     // Exit network
829     EtherExit();
830    
831     // Exit audio
832     AudioExit();
833    
834     // Exit video
835     VideoExit();
836    
837     // Exit external file system
838     ExtFSExit();
839    
840     // Exit drivers
841     SCSIExit();
842     CDROMExit();
843     DiskExit();
844     SonyExit();
845    
846     // Delete RAM area
847     if (ram_area_mapped)
848 gbeauche 1.8 vm_release((char *)RAM_BASE, RAMSize);
849 cebix 1.1
850     // Delete ROM area
851     if (rom_area_mapped)
852 gbeauche 1.4 vm_release((char *)ROM_BASE, ROM_AREA_SIZE);
853 cebix 1.1
854     // Delete Kernel Data area
855     if (kernel_area >= 0) {
856     shmdt((void *)KERNEL_DATA_BASE);
857     shmdt((void *)KERNEL_DATA2_BASE);
858     shmctl(kernel_area, IPC_RMID, NULL);
859     }
860    
861     // Delete Low Memory area
862     if (lm_area_mapped)
863     munmap((char *)0x0000, 0x3000);
864    
865     // Close /dev/zero
866     if (zero_fd > 0)
867     close(zero_fd);
868    
869     // Exit system routines
870     SysExit();
871    
872     // Exit preferences
873     PrefsExit();
874    
875     #ifdef ENABLE_MON
876     // Exit mon
877     mon_exit();
878     #endif
879    
880     // Close X11 server connection
881     if (x_display)
882     XCloseDisplay(x_display);
883    
884     exit(0);
885     }
886    
887    
888     /*
889     * Jump into Mac ROM, start 680x0 emulator
890     */
891    
892     #if EMULATED_PPC
893     void jump_to_rom(uint32 entry)
894     {
895     init_emul_ppc();
896     emul_ppc(entry);
897     }
898     #endif
899    
900    
901     /*
902     * Emulator thread function
903     */
904    
905     static void *emul_func(void *arg)
906     {
907     // We're now ready to receive signals
908     ready_for_signals = true;
909    
910     // Decrease priority, so more time-critical things like audio will work better
911     nice(1);
912    
913     // Jump to ROM boot routine
914     D(bug("Jumping to ROM\n"));
915     #if EMULATED_PPC
916     jump_to_rom(ROM_BASE + 0x310000);
917     #else
918     jump_to_rom(ROM_BASE + 0x310000, (uint32)emulator_data);
919     #endif
920     D(bug("Returned from ROM\n"));
921    
922     // We're no longer ready to receive signals
923     ready_for_signals = false;
924     return NULL;
925     }
926    
927    
928     #if !EMULATED_PPC
929     /*
930     * Execute 68k subroutine (must be ended with RTS)
931     * This must only be called by the emul_thread when in EMUL_OP mode
932     * r->a[7] is unused, the routine runs on the caller's stack
933     */
934    
935     void Execute68k(uint32 pc, M68kRegisters *r)
936     {
937     #if SAFE_EXEC_68K
938     if (ReadMacInt32(XLM_RUN_MODE) != MODE_EMUL_OP)
939     printf("FATAL: Execute68k() not called from EMUL_OP mode\n");
940     if (!pthread_equal(pthread_self(), emul_thread))
941     printf("FATAL: Execute68k() not called from emul_thread\n");
942     #endif
943     execute_68k(pc, r);
944     }
945    
946    
947     /*
948     * Execute 68k A-Trap from EMUL_OP routine
949     * r->a[7] is unused, the routine runs on the caller's stack
950     */
951    
952     void Execute68kTrap(uint16 trap, M68kRegisters *r)
953     {
954     uint16 proc[2] = {trap, M68K_RTS};
955     Execute68k((uint32)proc, r);
956     }
957    
958    
959     /*
960     * Execute PPC code from EMUL_OP routine (real mode switch)
961     */
962    
963     void ExecutePPC(void (*func)())
964     {
965     uint32 tvect[2] = {(uint32)func, 0}; // Fake TVECT
966     RoutineDescriptor desc = BUILD_PPC_ROUTINE_DESCRIPTOR(0, tvect);
967     M68kRegisters r;
968     Execute68k((uint32)&desc, &r);
969     }
970 gbeauche 1.7 #endif
971 cebix 1.1
972    
973     /*
974     * Quit emulator (cause return from jump_to_rom)
975     */
976    
977     void QuitEmulator(void)
978     {
979     #if EMULATED_PPC
980     Quit();
981     #else
982     quit_emulator();
983     #endif
984     }
985    
986    
987     /*
988     * Pause/resume emulator
989     */
990    
991     void PauseEmulator(void)
992     {
993     pthread_kill(emul_thread, SIGSTOP);
994     }
995    
996     void ResumeEmulator(void)
997     {
998     pthread_kill(emul_thread, SIGCONT);
999     }
1000    
1001    
1002     /*
1003     * Dump 68k registers
1004     */
1005    
1006     void Dump68kRegs(M68kRegisters *r)
1007     {
1008     // Display 68k registers
1009     for (int i=0; i<8; i++) {
1010     printf("d%d: %08x", i, r->d[i]);
1011     if (i == 3 || i == 7)
1012     printf("\n");
1013     else
1014     printf(", ");
1015     }
1016     for (int i=0; i<8; i++) {
1017     printf("a%d: %08x", i, r->a[i]);
1018     if (i == 3 || i == 7)
1019     printf("\n");
1020     else
1021     printf(", ");
1022     }
1023     }
1024    
1025    
1026     /*
1027     * Make code executable
1028     */
1029    
1030     void MakeExecutable(int dummy, void *start, uint32 length)
1031     {
1032 gbeauche 1.9 if (((uintptr)start >= ROM_BASE) && ((uintptr)start < (ROM_BASE + ROM_SIZE)))
1033 cebix 1.1 return;
1034 gbeauche 1.9 #if EMULATED_PPC
1035     FlushCodeCache((uintptr)start, (uintptr)start + length);
1036     #else
1037     flush_icache_range(start, (void *)((uintptr)start + length));
1038 cebix 1.1 #endif
1039     }
1040    
1041    
1042     /*
1043     * Patch things after system startup (gets called by disk driver accRun routine)
1044     */
1045    
1046     void PatchAfterStartup(void)
1047     {
1048 gbeauche 1.6 #if EMULATED_PPC
1049     ExecuteNative(NATIVE_VIDEO_INSTALL_ACCEL);
1050     #else
1051 cebix 1.1 ExecutePPC(VideoInstallAccel);
1052 gbeauche 1.6 #endif
1053 cebix 1.1 InstallExtFS();
1054     }
1055    
1056    
1057     /*
1058     * NVRAM watchdog thread (saves NVRAM every minute)
1059     */
1060    
1061     static void *nvram_func(void *arg)
1062     {
1063     struct timespec req = {60, 0}; // 1 minute
1064    
1065     for (;;) {
1066     pthread_testcancel();
1067     nanosleep(&req, NULL);
1068     pthread_testcancel();
1069     if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
1070     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
1071     SaveXPRAM();
1072     }
1073     }
1074     return NULL;
1075     }
1076    
1077    
1078     /*
1079     * 60Hz thread (really 60.15Hz)
1080     */
1081    
1082     static void *tick_func(void *arg)
1083     {
1084     int tick_counter = 0;
1085     struct timespec req = {0, 16625000};
1086    
1087     for (;;) {
1088    
1089     // Wait
1090     nanosleep(&req, NULL);
1091    
1092     #if !EMULATED_PPC
1093     // Did we crash?
1094     if (emul_thread_fatal) {
1095    
1096     // Yes, dump registers
1097     pt_regs *r = (pt_regs *)&sigsegv_regs;
1098     char str[256];
1099     sprintf(str, "SIGSEGV\n"
1100     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1101     " xer %08lx cr %08lx \n"
1102     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1103     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1104     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1105     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1106     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1107     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1108     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1109     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1110     r->nip, r->link, r->ctr, r->msr,
1111     r->xer, r->ccr,
1112     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1113     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1114     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1115     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1116     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1117     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1118     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1119     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1120     printf(str);
1121     VideoQuitFullScreen();
1122    
1123     #ifdef ENABLE_MON
1124     // Start up mon in real-mode
1125     printf("Welcome to the sheep factory.\n");
1126     char *arg[4] = {"mon", "-m", "-r", NULL};
1127     mon(3, arg);
1128     #endif
1129     return NULL;
1130     }
1131     #endif
1132    
1133     // Pseudo Mac 1Hz interrupt, update local time
1134     if (++tick_counter > 60) {
1135     tick_counter = 0;
1136     WriteMacInt32(0x20c, TimerDateTime());
1137     }
1138    
1139     // Trigger 60Hz interrupt
1140     if (ReadMacInt32(XLM_IRQ_NEST) == 0) {
1141     SetInterruptFlag(INTFLAG_VIA);
1142     TriggerInterrupt();
1143     }
1144     }
1145     return NULL;
1146     }
1147    
1148    
1149     /*
1150 cebix 1.2 * Pthread configuration
1151     */
1152    
1153     void Set_pthread_attr(pthread_attr_t *attr, int priority)
1154     {
1155 gbeauche 1.14 #ifdef HAVE_PTHREADS
1156     pthread_attr_init(attr);
1157     #if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
1158     // Some of these only work for superuser
1159     if (geteuid() == 0) {
1160     pthread_attr_setinheritsched(attr, PTHREAD_EXPLICIT_SCHED);
1161     pthread_attr_setschedpolicy(attr, SCHED_FIFO);
1162     struct sched_param fifo_param;
1163     fifo_param.sched_priority = ((sched_get_priority_min(SCHED_FIFO) +
1164     sched_get_priority_max(SCHED_FIFO)) / 2 +
1165     priority);
1166     pthread_attr_setschedparam(attr, &fifo_param);
1167     }
1168     if (pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM) != 0) {
1169     #ifdef PTHREAD_SCOPE_BOUND_NP
1170     // If system scope is not available (eg. we're not running
1171     // with CAP_SCHED_MGT capability on an SGI box), try bound
1172     // scope. It exposes pthread scheduling to the kernel,
1173     // without setting realtime priority.
1174     pthread_attr_setscope(attr, PTHREAD_SCOPE_BOUND_NP);
1175     #endif
1176     }
1177     #endif
1178     #endif
1179 cebix 1.2 }
1180    
1181    
1182     /*
1183 cebix 1.1 * Mutexes
1184     */
1185    
1186 gbeauche 1.7 #ifdef HAVE_PTHREADS
1187    
1188     struct B2_mutex {
1189     B2_mutex() {
1190     pthread_mutexattr_t attr;
1191     pthread_mutexattr_init(&attr);
1192     // Initialize the mutex for priority inheritance --
1193     // required for accurate timing.
1194     #ifdef HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL
1195     pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
1196     #endif
1197     #if defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE) && defined(PTHREAD_MUTEX_NORMAL)
1198     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
1199     #endif
1200     #ifdef HAVE_PTHREAD_MUTEXATTR_SETPSHARED
1201     pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);
1202     #endif
1203     pthread_mutex_init(&m, &attr);
1204     pthread_mutexattr_destroy(&attr);
1205     }
1206     ~B2_mutex() {
1207     pthread_mutex_trylock(&m); // Make sure it's locked before
1208     pthread_mutex_unlock(&m); // unlocking it.
1209     pthread_mutex_destroy(&m);
1210     }
1211     pthread_mutex_t m;
1212     };
1213    
1214     B2_mutex *B2_create_mutex(void)
1215     {
1216     return new B2_mutex;
1217     }
1218    
1219     void B2_lock_mutex(B2_mutex *mutex)
1220     {
1221     pthread_mutex_lock(&mutex->m);
1222     }
1223    
1224     void B2_unlock_mutex(B2_mutex *mutex)
1225     {
1226     pthread_mutex_unlock(&mutex->m);
1227     }
1228    
1229     void B2_delete_mutex(B2_mutex *mutex)
1230     {
1231     delete mutex;
1232     }
1233    
1234     #else
1235    
1236 cebix 1.1 struct B2_mutex {
1237     int dummy;
1238     };
1239    
1240     B2_mutex *B2_create_mutex(void)
1241     {
1242     return new B2_mutex;
1243     }
1244    
1245     void B2_lock_mutex(B2_mutex *mutex)
1246     {
1247     }
1248    
1249     void B2_unlock_mutex(B2_mutex *mutex)
1250     {
1251     }
1252    
1253     void B2_delete_mutex(B2_mutex *mutex)
1254     {
1255     delete mutex;
1256     }
1257    
1258 gbeauche 1.7 #endif
1259    
1260 cebix 1.1
1261     /*
1262     * Trigger signal USR2 from another thread
1263     */
1264    
1265 gbeauche 1.8 #if !EMULATED_PPC || ASYNC_IRQ
1266 cebix 1.1 void TriggerInterrupt(void)
1267     {
1268     if (ready_for_signals)
1269     pthread_kill(emul_thread, SIGUSR2);
1270     }
1271 gbeauche 1.7 #endif
1272 cebix 1.1
1273    
1274     /*
1275     * Interrupt flags (must be handled atomically!)
1276     */
1277    
1278     volatile uint32 InterruptFlags = 0;
1279    
1280     void SetInterruptFlag(uint32 flag)
1281     {
1282     atomic_or((int *)&InterruptFlags, flag);
1283     }
1284    
1285     void ClearInterruptFlag(uint32 flag)
1286     {
1287     atomic_and((int *)&InterruptFlags, ~flag);
1288     }
1289    
1290    
1291     /*
1292     * Disable interrupts
1293     */
1294    
1295     void DisableInterrupt(void)
1296     {
1297 gbeauche 1.7 atomic_add((int *)XLM_IRQ_NEST, 1);
1298 cebix 1.1 }
1299    
1300    
1301     /*
1302     * Enable interrupts
1303     */
1304    
1305     void EnableInterrupt(void)
1306     {
1307 gbeauche 1.7 atomic_add((int *)XLM_IRQ_NEST, -1);
1308 cebix 1.1 }
1309    
1310    
1311     /*
1312     * USR2 handler
1313     */
1314    
1315 gbeauche 1.8 #if EMULATED_PPC
1316     static void sigusr2_handler(int sig)
1317     {
1318     #if ASYNC_IRQ
1319     extern void HandleInterrupt(void);
1320     HandleInterrupt();
1321     #endif
1322     }
1323     #else
1324 cebix 1.1 static void sigusr2_handler(int sig, sigcontext_struct *sc)
1325     {
1326     pt_regs *r = sc->regs;
1327    
1328     // Do nothing if interrupts are disabled
1329     if (*(int32 *)XLM_IRQ_NEST > 0)
1330     return;
1331    
1332     // Disable MacOS stack sniffer
1333     WriteMacInt32(0x110, 0);
1334    
1335     // Interrupt action depends on current run mode
1336     switch (ReadMacInt32(XLM_RUN_MODE)) {
1337     case MODE_68K:
1338     // 68k emulator active, trigger 68k interrupt level 1
1339     WriteMacInt16(ntohl(kernel_data->v[0x67c >> 2]), 1);
1340     r->ccr |= ntohl(kernel_data->v[0x674 >> 2]);
1341     break;
1342    
1343     #if INTERRUPTS_IN_NATIVE_MODE
1344     case MODE_NATIVE:
1345     // 68k emulator inactive, in nanokernel?
1346     if (r->gpr[1] != KernelDataAddr) {
1347     // Prepare for 68k interrupt level 1
1348     WriteMacInt16(ntohl(kernel_data->v[0x67c >> 2]), 1);
1349     WriteMacInt32(ntohl(kernel_data->v[0x658 >> 2]) + 0xdc, ReadMacInt32(ntohl(kernel_data->v[0x658 >> 2]) + 0xdc) | ntohl(kernel_data->v[0x674 >> 2]));
1350    
1351     // Execute nanokernel interrupt routine (this will activate the 68k emulator)
1352     atomic_add((int32 *)XLM_IRQ_NEST, 1);
1353     if (ROMType == ROMTYPE_NEWWORLD)
1354     ppc_interrupt(ROM_BASE + 0x312b1c, KernelDataAddr);
1355     else
1356     ppc_interrupt(ROM_BASE + 0x312a3c, KernelDataAddr);
1357     }
1358     break;
1359     #endif
1360    
1361     #if INTERRUPTS_IN_EMUL_OP_MODE
1362     case MODE_EMUL_OP:
1363     // 68k emulator active, within EMUL_OP routine, execute 68k interrupt routine directly when interrupt level is 0
1364     if ((ReadMacInt32(XLM_68K_R25) & 7) == 0) {
1365    
1366     // Set extra stack for SIGSEGV handler
1367     struct sigaltstack new_stack;
1368     new_stack.ss_sp = extra_stack;
1369     new_stack.ss_flags = 0;
1370     new_stack.ss_size = SIG_STACK_SIZE;
1371     sigaltstack(&new_stack, NULL);
1372     #if 1
1373     // Execute full 68k interrupt routine
1374     M68kRegisters r;
1375     uint32 old_r25 = ReadMacInt32(XLM_68K_R25); // Save interrupt level
1376     WriteMacInt32(XLM_68K_R25, 0x21); // Execute with interrupt level 1
1377     static const uint16 proc[] = {
1378     0x3f3c, 0x0000, // move.w #$0000,-(sp) (fake format word)
1379     0x487a, 0x000a, // pea @1(pc) (return address)
1380     0x40e7, // move sr,-(sp) (saved SR)
1381     0x2078, 0x0064, // move.l $64,a0
1382     0x4ed0, // jmp (a0)
1383     M68K_RTS // @1
1384     };
1385     Execute68k((uint32)proc, &r);
1386     WriteMacInt32(XLM_68K_R25, old_r25); // Restore interrupt level
1387     #else
1388     // Only update cursor
1389     if (HasMacStarted()) {
1390     if (InterruptFlags & INTFLAG_VIA) {
1391     ClearInterruptFlag(INTFLAG_VIA);
1392     ADBInterrupt();
1393     ExecutePPC(VideoVBL);
1394     }
1395     }
1396     #endif
1397     // Reset normal signal stack
1398     new_stack.ss_sp = sig_stack;
1399     new_stack.ss_flags = 0;
1400     new_stack.ss_size = SIG_STACK_SIZE;
1401     sigaltstack(&new_stack, NULL);
1402     }
1403     break;
1404     #endif
1405     }
1406     }
1407 gbeauche 1.8 #endif
1408 cebix 1.1
1409    
1410     /*
1411     * SIGSEGV handler
1412     */
1413    
1414 gbeauche 1.8 #if !EMULATED_PPC
1415 cebix 1.1 static void sigsegv_handler(int sig, sigcontext_struct *sc)
1416     {
1417     pt_regs *r = sc->regs;
1418 gbeauche 1.5
1419     // Get effective address
1420     uint32 addr = r->dar;
1421    
1422     #if ENABLE_VOSF
1423     // Handle screen fault.
1424     extern bool Screen_fault_handler(sigsegv_address_t fault_address, sigsegv_address_t fault_instruction);
1425     if (Screen_fault_handler((sigsegv_address_t)addr, (sigsegv_address_t)r->nip))
1426     return;
1427     #endif
1428    
1429 cebix 1.1 num_segv++;
1430    
1431     // Fault in Mac ROM or RAM?
1432     bool mac_fault = (r->nip >= ROM_BASE) && (r->nip < (ROM_BASE + ROM_AREA_SIZE)) || (r->nip >= RAMBase) && (r->nip < (RAMBase + RAMSize));
1433     if (mac_fault) {
1434    
1435     // "VM settings" during MacOS 8 installation
1436     if (r->nip == ROM_BASE + 0x488160 && r->gpr[20] == 0xf8000000) {
1437     r->nip += 4;
1438     r->gpr[8] = 0;
1439     return;
1440    
1441     // MacOS 8.5 installation
1442     } else if (r->nip == ROM_BASE + 0x488140 && r->gpr[16] == 0xf8000000) {
1443     r->nip += 4;
1444     r->gpr[8] = 0;
1445     return;
1446    
1447     // MacOS 8 serial drivers on startup
1448     } else if (r->nip == ROM_BASE + 0x48e080 && (r->gpr[8] == 0xf3012002 || r->gpr[8] == 0xf3012000)) {
1449     r->nip += 4;
1450     r->gpr[8] = 0;
1451     return;
1452    
1453     // MacOS 8.1 serial drivers on startup
1454     } else if (r->nip == ROM_BASE + 0x48c5e0 && (r->gpr[20] == 0xf3012002 || r->gpr[20] == 0xf3012000)) {
1455     r->nip += 4;
1456     return;
1457     } else if (r->nip == ROM_BASE + 0x4a10a0 && (r->gpr[20] == 0xf3012002 || r->gpr[20] == 0xf3012000)) {
1458     r->nip += 4;
1459     return;
1460     }
1461    
1462 gbeauche 1.5 // Get opcode and divide into fields
1463     uint32 opcode = *((uint32 *)r->nip);
1464     uint32 primop = opcode >> 26;
1465     uint32 exop = (opcode >> 1) & 0x3ff;
1466     uint32 ra = (opcode >> 16) & 0x1f;
1467     uint32 rb = (opcode >> 11) & 0x1f;
1468     uint32 rd = (opcode >> 21) & 0x1f;
1469     int32 imm = (int16)(opcode & 0xffff);
1470    
1471 cebix 1.1 // Analyze opcode
1472     enum {
1473     TYPE_UNKNOWN,
1474     TYPE_LOAD,
1475     TYPE_STORE
1476     } transfer_type = TYPE_UNKNOWN;
1477     enum {
1478     SIZE_UNKNOWN,
1479     SIZE_BYTE,
1480     SIZE_HALFWORD,
1481     SIZE_WORD
1482     } transfer_size = SIZE_UNKNOWN;
1483     enum {
1484     MODE_UNKNOWN,
1485     MODE_NORM,
1486     MODE_U,
1487     MODE_X,
1488     MODE_UX
1489     } addr_mode = MODE_UNKNOWN;
1490     switch (primop) {
1491     case 31:
1492     switch (exop) {
1493     case 23: // lwzx
1494     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
1495     case 55: // lwzux
1496     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
1497     case 87: // lbzx
1498     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
1499     case 119: // lbzux
1500     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
1501     case 151: // stwx
1502     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
1503     case 183: // stwux
1504     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
1505     case 215: // stbx
1506     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
1507     case 247: // stbux
1508     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
1509     case 279: // lhzx
1510     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1511     case 311: // lhzux
1512     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1513     case 343: // lhax
1514     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1515     case 375: // lhaux
1516     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1517     case 407: // sthx
1518     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1519     case 439: // sthux
1520     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1521     }
1522     break;
1523    
1524     case 32: // lwz
1525     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
1526     case 33: // lwzu
1527     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
1528     case 34: // lbz
1529     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
1530     case 35: // lbzu
1531     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
1532     case 36: // stw
1533     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
1534     case 37: // stwu
1535     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
1536     case 38: // stb
1537     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
1538     case 39: // stbu
1539     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
1540     case 40: // lhz
1541     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1542     case 41: // lhzu
1543     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1544     case 42: // lha
1545     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1546     case 43: // lhau
1547     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1548     case 44: // sth
1549     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1550     case 45: // sthu
1551     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1552     }
1553    
1554     // Ignore ROM writes
1555     if (transfer_type == TYPE_STORE && addr >= ROM_BASE && addr < ROM_BASE + ROM_SIZE) {
1556     // D(bug("WARNING: %s write access to ROM at %08lx, pc %08lx\n", transfer_size == SIZE_BYTE ? "Byte" : transfer_size == SIZE_HALFWORD ? "Halfword" : "Word", addr, r->nip));
1557     if (addr_mode == MODE_U || addr_mode == MODE_UX)
1558     r->gpr[ra] = addr;
1559     r->nip += 4;
1560     goto rti;
1561     }
1562    
1563     // Ignore illegal memory accesses?
1564     if (PrefsFindBool("ignoresegv")) {
1565     if (addr_mode == MODE_U || addr_mode == MODE_UX)
1566     r->gpr[ra] = addr;
1567     if (transfer_type == TYPE_LOAD)
1568     r->gpr[rd] = 0;
1569     r->nip += 4;
1570     goto rti;
1571     }
1572    
1573     // In GUI mode, show error alert
1574     if (!PrefsFindBool("nogui")) {
1575     char str[256];
1576     if (transfer_type == TYPE_LOAD || transfer_type == TYPE_STORE)
1577     sprintf(str, GetString(STR_MEM_ACCESS_ERR), transfer_size == SIZE_BYTE ? "byte" : transfer_size == SIZE_HALFWORD ? "halfword" : "word", transfer_type == TYPE_LOAD ? GetString(STR_MEM_ACCESS_READ) : GetString(STR_MEM_ACCESS_WRITE), addr, r->nip, r->gpr[24], r->gpr[1]);
1578     else
1579     sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->nip, r->gpr[24], r->gpr[1], opcode);
1580     ErrorAlert(str);
1581     QuitEmulator();
1582     return;
1583     }
1584     }
1585    
1586     // For all other errors, jump into debugger (sort of...)
1587     if (!ready_for_signals) {
1588     printf("SIGSEGV\n");
1589     printf(" sigcontext %p, pt_regs %p\n", sc, r);
1590     printf(
1591     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1592     " xer %08lx cr %08lx \n"
1593     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1594     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1595     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1596     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1597     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1598     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1599     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1600     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1601     r->nip, r->link, r->ctr, r->msr,
1602     r->xer, r->ccr,
1603     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1604     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1605     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1606     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1607     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1608     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1609     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1610     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1611     exit(1);
1612     QuitEmulator();
1613     return;
1614     } else {
1615     // We crashed. Save registers, tell tick thread and loop forever
1616     sigsegv_regs = *(sigregs *)r;
1617     emul_thread_fatal = true;
1618     for (;;) ;
1619     }
1620     rti:;
1621     }
1622    
1623    
1624     /*
1625     * SIGILL handler
1626     */
1627    
1628     static void sigill_handler(int sig, sigcontext_struct *sc)
1629     {
1630     pt_regs *r = sc->regs;
1631     char str[256];
1632    
1633     // Fault in Mac ROM or RAM?
1634     bool mac_fault = (r->nip >= ROM_BASE) && (r->nip < (ROM_BASE + ROM_AREA_SIZE)) || (r->nip >= RAMBase) && (r->nip < (RAMBase + RAMSize));
1635     if (mac_fault) {
1636    
1637     // Get opcode and divide into fields
1638     uint32 opcode = *((uint32 *)r->nip);
1639     uint32 primop = opcode >> 26;
1640     uint32 exop = (opcode >> 1) & 0x3ff;
1641     uint32 ra = (opcode >> 16) & 0x1f;
1642     uint32 rb = (opcode >> 11) & 0x1f;
1643     uint32 rd = (opcode >> 21) & 0x1f;
1644     int32 imm = (int16)(opcode & 0xffff);
1645    
1646     switch (primop) {
1647     case 9: // POWER instructions
1648     case 22:
1649     power_inst: sprintf(str, GetString(STR_POWER_INSTRUCTION_ERR), r->nip, r->gpr[1], opcode);
1650     ErrorAlert(str);
1651     QuitEmulator();
1652     return;
1653    
1654     case 31:
1655     switch (exop) {
1656     case 83: // mfmsr
1657     r->gpr[rd] = 0xf072;
1658     r->nip += 4;
1659     goto rti;
1660    
1661     case 210: // mtsr
1662     case 242: // mtsrin
1663     case 306: // tlbie
1664     r->nip += 4;
1665     goto rti;
1666    
1667     case 339: { // mfspr
1668     int spr = ra | (rb << 5);
1669     switch (spr) {
1670     case 0: // MQ
1671     case 22: // DEC
1672     case 952: // MMCR0
1673     case 953: // PMC1
1674     case 954: // PMC2
1675     case 955: // SIA
1676     case 956: // MMCR1
1677     case 957: // PMC3
1678     case 958: // PMC4
1679     case 959: // SDA
1680     r->nip += 4;
1681     goto rti;
1682     case 25: // SDR1
1683     r->gpr[rd] = 0xdead001f;
1684     r->nip += 4;
1685     goto rti;
1686     case 287: // PVR
1687     r->gpr[rd] = PVR;
1688     r->nip += 4;
1689     goto rti;
1690     }
1691     break;
1692     }
1693    
1694     case 467: { // mtspr
1695     int spr = ra | (rb << 5);
1696     switch (spr) {
1697     case 0: // MQ
1698     case 22: // DEC
1699     case 275: // SPRG3
1700     case 528: // IBAT0U
1701     case 529: // IBAT0L
1702     case 530: // IBAT1U
1703     case 531: // IBAT1L
1704     case 532: // IBAT2U
1705     case 533: // IBAT2L
1706     case 534: // IBAT3U
1707     case 535: // IBAT3L
1708     case 536: // DBAT0U
1709     case 537: // DBAT0L
1710     case 538: // DBAT1U
1711     case 539: // DBAT1L
1712     case 540: // DBAT2U
1713     case 541: // DBAT2L
1714     case 542: // DBAT3U
1715     case 543: // DBAT3L
1716     case 952: // MMCR0
1717     case 953: // PMC1
1718     case 954: // PMC2
1719     case 955: // SIA
1720     case 956: // MMCR1
1721     case 957: // PMC3
1722     case 958: // PMC4
1723     case 959: // SDA
1724     r->nip += 4;
1725     goto rti;
1726     }
1727     break;
1728     }
1729    
1730     case 29: case 107: case 152: case 153: // POWER instructions
1731     case 184: case 216: case 217: case 248:
1732     case 264: case 277: case 331: case 360:
1733     case 363: case 488: case 531: case 537:
1734     case 541: case 664: case 665: case 696:
1735     case 728: case 729: case 760: case 920:
1736     case 921: case 952:
1737     goto power_inst;
1738     }
1739     }
1740    
1741     // In GUI mode, show error alert
1742     if (!PrefsFindBool("nogui")) {
1743     sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->nip, r->gpr[24], r->gpr[1], opcode);
1744     ErrorAlert(str);
1745     QuitEmulator();
1746     return;
1747     }
1748     }
1749    
1750     // For all other errors, jump into debugger (sort of...)
1751     if (!ready_for_signals) {
1752     printf("SIGILL\n");
1753     printf(" sigcontext %p, pt_regs %p\n", sc, r);
1754     printf(
1755     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1756     " xer %08lx cr %08lx \n"
1757     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1758     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1759     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1760     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1761     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1762     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1763     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1764     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1765     r->nip, r->link, r->ctr, r->msr,
1766     r->xer, r->ccr,
1767     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1768     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1769     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1770     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1771     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1772     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1773     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1774     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1775     exit(1);
1776     QuitEmulator();
1777     return;
1778     } else {
1779     // We crashed. Save registers, tell tick thread and loop forever
1780     sigsegv_regs = *(sigregs *)r;
1781     emul_thread_fatal = true;
1782     for (;;) ;
1783     }
1784     rti:;
1785     }
1786     #endif
1787    
1788    
1789     /*
1790     * Display alert
1791     */
1792    
1793     #ifdef ENABLE_GTK
1794     static void dl_destroyed(void)
1795     {
1796     gtk_main_quit();
1797     }
1798    
1799     static void dl_quit(GtkWidget *dialog)
1800     {
1801     gtk_widget_destroy(dialog);
1802     }
1803    
1804     void display_alert(int title_id, int prefix_id, int button_id, const char *text)
1805     {
1806     char str[256];
1807     sprintf(str, GetString(prefix_id), text);
1808    
1809     GtkWidget *dialog = gtk_dialog_new();
1810     gtk_window_set_title(GTK_WINDOW(dialog), GetString(title_id));
1811     gtk_container_border_width(GTK_CONTAINER(dialog), 5);
1812     gtk_widget_set_uposition(GTK_WIDGET(dialog), 100, 150);
1813     gtk_signal_connect(GTK_OBJECT(dialog), "destroy", GTK_SIGNAL_FUNC(dl_destroyed), NULL);
1814    
1815     GtkWidget *label = gtk_label_new(str);
1816     gtk_widget_show(label);
1817     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, TRUE, TRUE, 0);
1818    
1819     GtkWidget *button = gtk_button_new_with_label(GetString(button_id));
1820     gtk_widget_show(button);
1821     gtk_signal_connect_object(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(dl_quit), GTK_OBJECT(dialog));
1822     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area), button, FALSE, FALSE, 0);
1823     GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1824     gtk_widget_grab_default(button);
1825     gtk_widget_show(dialog);
1826    
1827     gtk_main();
1828     }
1829     #endif
1830    
1831    
1832     /*
1833     * Display error alert
1834     */
1835    
1836     void ErrorAlert(const char *text)
1837     {
1838     #ifdef ENABLE_GTK
1839     if (PrefsFindBool("nogui") || x_display == NULL) {
1840     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1841     return;
1842     }
1843     VideoQuitFullScreen();
1844     display_alert(STR_ERROR_ALERT_TITLE, STR_GUI_ERROR_PREFIX, STR_QUIT_BUTTON, text);
1845     #else
1846     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1847     #endif
1848     }
1849    
1850    
1851     /*
1852     * Display warning alert
1853     */
1854    
1855     void WarningAlert(const char *text)
1856     {
1857     #ifdef ENABLE_GTK
1858     if (PrefsFindBool("nogui") || x_display == NULL) {
1859     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1860     return;
1861     }
1862     display_alert(STR_WARNING_ALERT_TITLE, STR_GUI_WARNING_PREFIX, STR_OK_BUTTON, text);
1863     #else
1864     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1865     #endif
1866     }
1867    
1868    
1869     /*
1870     * Display choice alert
1871     */
1872    
1873     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1874     {
1875     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1876     return false; //!!
1877     }