ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.20
Committed: 2003-12-05T13:37:54Z (20 years, 11 months ago) by gbeauche
Branch: MAIN
Changes since 1.19: +36 -5 lines
Log Message:
Use an alternate stack base while servicing PowerPC interrupts.

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