ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.51
Committed: 2004-07-19T19:42:21Z (20 years, 3 months ago) by gbeauche
Branch: MAIN
Changes since 1.50: +3 -0 lines
Log Message:
SDL audio support

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * main_unix.cpp - Emulation core, Unix implementation
3     *
4 cebix 1.25 * SheepShaver (C) 1997-2004 Christian Bauer and Marc Hellwig
5 cebix 1.1 *
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 gbeauche 1.33 * There is apparently another problem when processing signals. In
69     * fullscreen mode, we get quick updates of the mouse position. This
70     * causes an increased number of calls to TriggerInterrupt(). And,
71     * since IRQ_NEST is not fully handled atomically, nested calls to
72     * ppc_interrupt() may cause stack corruption to eventually crash the
73     * emulator.
74     *
75     * FIXME:
76     * The current solution is to allocate another signal stack when
77     * processing ppc_interrupt(). However, it may be better to detect
78     * the INTFLAG_ADB case and handle it specifically with some extra mutex?
79     *
80 cebix 1.1 * TODO:
81     * check if SIGSEGV handler works for all registers (including FP!)
82     */
83    
84     #include <unistd.h>
85     #include <fcntl.h>
86     #include <time.h>
87     #include <errno.h>
88     #include <stdio.h>
89     #include <stdlib.h>
90     #include <string.h>
91     #include <pthread.h>
92     #include <sys/mman.h>
93     #include <sys/ipc.h>
94     #include <sys/shm.h>
95     #include <signal.h>
96    
97     #include "sysdeps.h"
98     #include "main.h"
99     #include "version.h"
100     #include "prefs.h"
101     #include "prefs_editor.h"
102     #include "cpu_emulation.h"
103     #include "emul_op.h"
104     #include "xlowmem.h"
105     #include "xpram.h"
106     #include "timer.h"
107     #include "adb.h"
108     #include "sony.h"
109     #include "disk.h"
110     #include "cdrom.h"
111     #include "scsi.h"
112     #include "video.h"
113     #include "audio.h"
114     #include "ether.h"
115     #include "serial.h"
116     #include "clip.h"
117     #include "extfs.h"
118     #include "sys.h"
119     #include "macos_util.h"
120     #include "rom_patches.h"
121     #include "user_strings.h"
122 gbeauche 1.4 #include "vm_alloc.h"
123 gbeauche 1.5 #include "sigsegv.h"
124 gbeauche 1.15 #include "thunks.h"
125 cebix 1.1
126     #define DEBUG 0
127     #include "debug.h"
128    
129    
130 gbeauche 1.47 #ifdef HAVE_DIRENT_H
131     #include <dirent.h>
132     #endif
133    
134 gbeauche 1.42 #ifdef USE_SDL
135     #include <SDL.h>
136     #endif
137    
138     #ifndef USE_SDL_VIDEO
139 cebix 1.1 #include <X11/Xlib.h>
140 gbeauche 1.42 #endif
141 cebix 1.1
142     #ifdef ENABLE_GTK
143     #include <gtk/gtk.h>
144     #endif
145    
146     #ifdef ENABLE_XF86_DGA
147     #include <X11/Xlib.h>
148     #include <X11/Xutil.h>
149     #include <X11/extensions/xf86dga.h>
150     #endif
151    
152     #ifdef ENABLE_MON
153     #include "mon.h"
154     #endif
155    
156    
157 gbeauche 1.23 // Enable emulation of unaligned lmw/stmw?
158     #define EMULATE_UNALIGNED_LOADSTORE_MULTIPLE 1
159    
160 cebix 1.1 // Enable Execute68k() safety checks?
161     #define SAFE_EXEC_68K 0
162    
163     // Interrupts in EMUL_OP mode?
164     #define INTERRUPTS_IN_EMUL_OP_MODE 1
165    
166     // Interrupts in native mode?
167     #define INTERRUPTS_IN_NATIVE_MODE 1
168    
169 gbeauche 1.33 // Number of alternate stacks for signal handlers?
170     #define SIG_STACK_COUNT 4
171    
172 cebix 1.1
173     // Constants
174     const char ROM_FILE_NAME[] = "ROM";
175     const char ROM_FILE_NAME2[] = "Mac OS ROM";
176    
177 gbeauche 1.15 const uintptr RAM_BASE = 0x20000000; // Base address of RAM
178 cebix 1.1 const uint32 SIG_STACK_SIZE = 0x10000; // Size of signal stack
179    
180    
181     #if !EMULATED_PPC
182 gbeauche 1.26 struct sigregs {
183     uint32 nip;
184     uint32 link;
185     uint32 ctr;
186     uint32 msr;
187     uint32 xer;
188     uint32 ccr;
189     uint32 gpr[32];
190     };
191 cebix 1.1
192 gbeauche 1.26 #if defined(__linux__)
193 gbeauche 1.28 #include <sys/ucontext.h>
194     #define MACHINE_REGISTERS(scp) ((machine_regs *)(((ucontext_t *)scp)->uc_mcontext.regs))
195    
196 gbeauche 1.26 struct machine_regs : public pt_regs
197     {
198     u_long & cr() { return pt_regs::ccr; }
199     uint32 cr() const { return pt_regs::ccr; }
200     uint32 lr() const { return pt_regs::link; }
201     uint32 ctr() const { return pt_regs::ctr; }
202     uint32 xer() const { return pt_regs::xer; }
203     uint32 msr() const { return pt_regs::msr; }
204     uint32 dar() const { return pt_regs::dar; }
205     u_long & pc() { return pt_regs::nip; }
206     uint32 pc() const { return pt_regs::nip; }
207     u_long & gpr(int i) { return pt_regs::gpr[i]; }
208     uint32 gpr(int i) const { return pt_regs::gpr[i]; }
209 cebix 1.1 };
210 gbeauche 1.28 #endif
211    
212     #if defined(__APPLE__) && defined(__MACH__)
213     #include <sys/signal.h>
214     extern "C" int sigaltstack(const struct sigaltstack *ss, struct sigaltstack *oss);
215 gbeauche 1.26
216     #include <sys/ucontext.h>
217 gbeauche 1.28 #define MACHINE_REGISTERS(scp) ((machine_regs *)(((ucontext_t *)scp)->uc_mcontext))
218 gbeauche 1.26
219     struct machine_regs : public mcontext
220     {
221     uint32 & cr() { return ss.cr; }
222     uint32 cr() const { return ss.cr; }
223     uint32 lr() const { return ss.lr; }
224     uint32 ctr() const { return ss.ctr; }
225     uint32 xer() const { return ss.xer; }
226     uint32 msr() const { return ss.srr1; }
227     uint32 dar() const { return es.dar; }
228     uint32 & pc() { return ss.srr0; }
229     uint32 pc() const { return ss.srr0; }
230     uint32 & gpr(int i) { return (&ss.r0)[i]; }
231     uint32 gpr(int i) const { return (&ss.r0)[i]; }
232     };
233     #endif
234    
235     static void build_sigregs(sigregs *srp, machine_regs *mrp)
236     {
237     srp->nip = mrp->pc();
238     srp->link = mrp->lr();
239     srp->ctr = mrp->ctr();
240     srp->msr = mrp->msr();
241     srp->xer = mrp->xer();
242     srp->ccr = mrp->cr();
243     for (int i = 0; i < 32; i++)
244     srp->gpr[i] = mrp->gpr(i);
245     }
246 gbeauche 1.33
247     static struct sigaltstack sig_stacks[SIG_STACK_COUNT]; // Stacks for signal handlers
248     static int sig_stack_id = 0; // Stack slot currently used
249    
250     static inline void sig_stack_acquire(void)
251     {
252     if (++sig_stack_id == SIG_STACK_COUNT) {
253     printf("FATAL: signal stack overflow\n");
254     return;
255     }
256     sigaltstack(&sig_stacks[sig_stack_id], NULL);
257     }
258    
259     static inline void sig_stack_release(void)
260     {
261     if (--sig_stack_id < 0) {
262     printf("FATAL: signal stack underflow\n");
263     return;
264     }
265     sigaltstack(&sig_stacks[sig_stack_id], NULL);
266     }
267 cebix 1.1 #endif
268    
269    
270     // Global variables (exported)
271     #if !EMULATED_PPC
272     void *TOC; // Small data pointer (r13)
273     #endif
274     uint32 RAMBase; // Base address of Mac RAM
275     uint32 RAMSize; // Size of Mac RAM
276     uint32 KernelDataAddr; // Address of Kernel Data
277     uint32 BootGlobsAddr; // Address of BootGlobs structure at top of Mac RAM
278 gbeauche 1.36 uint32 DRCacheAddr; // Address of DR Cache
279 cebix 1.1 uint32 PVR; // Theoretical PVR
280     int64 CPUClockSpeed; // Processor clock speed (Hz)
281     int64 BusClockSpeed; // Bus clock speed (Hz)
282 gbeauche 1.47 int64 TimebaseSpeed; // Timebase clock speed (Hz)
283 cebix 1.1
284    
285     // Global variables
286 gbeauche 1.42 #ifndef USE_SDL_VIDEO
287 gbeauche 1.11 char *x_display_name = NULL; // X11 display name
288 cebix 1.1 Display *x_display = NULL; // X11 display handle
289 gbeauche 1.21 #ifdef X11_LOCK_TYPE
290     X11_LOCK_TYPE x_display_lock = X11_LOCK_INIT; // X11 display lock
291     #endif
292 gbeauche 1.42 #endif
293 cebix 1.1
294     static int zero_fd = 0; // FD of /dev/zero
295     static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
296     static int kernel_area = -1; // SHM ID of Kernel Data area
297     static bool rom_area_mapped = false; // Flag: Mac ROM mmap()ped
298     static bool ram_area_mapped = false; // Flag: Mac RAM mmap()ped
299 gbeauche 1.36 static bool dr_cache_area_mapped = false; // Flag: Mac DR Cache mmap()ped
300     static bool dr_emulator_area_mapped = false;// Flag: Mac DR Emulator mmap()ped
301 cebix 1.1 static KernelData *kernel_data; // Pointer to Kernel Data
302     static EmulatorData *emulator_data;
303    
304     static uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes
305    
306     static bool nvram_thread_active = false; // Flag: NVRAM watchdog installed
307 gbeauche 1.40 static volatile bool nvram_thread_cancel; // Flag: Cancel NVRAM thread
308 cebix 1.1 static pthread_t nvram_thread; // NVRAM watchdog
309     static bool tick_thread_active = false; // Flag: MacOS thread installed
310 gbeauche 1.40 static volatile bool tick_thread_cancel; // Flag: Cancel 60Hz thread
311 cebix 1.1 static pthread_t tick_thread; // 60Hz thread
312     static pthread_t emul_thread; // MacOS thread
313    
314     static bool ready_for_signals = false; // Handler installed, signals can be sent
315     static int64 num_segv = 0; // Number of handled SEGV signals
316    
317 gbeauche 1.6 static struct sigaction sigusr2_action; // Interrupt signal (of emulator thread)
318 gbeauche 1.20 #if EMULATED_PPC
319     static uintptr sig_stack = 0; // Stack for PowerPC interrupt routine
320     #else
321 cebix 1.1 static struct sigaction sigsegv_action; // Data access exception signal (of emulator thread)
322     static struct sigaction sigill_action; // Illegal instruction signal (of emulator thread)
323     static bool emul_thread_fatal = false; // Flag: MacOS thread crashed, tick thread shall dump debug output
324     static sigregs sigsegv_regs; // Register dump when crashed
325 gbeauche 1.23 static const char *crash_reason = NULL; // Reason of the crash (SIGSEGV, SIGBUS, SIGILL)
326 cebix 1.1 #endif
327    
328 gbeauche 1.31 uint32 SheepMem::page_size; // Size of a native page
329 gbeauche 1.18 uintptr SheepMem::zero_page = 0; // Address of ro page filled in with zeros
330 gbeauche 1.15 uintptr SheepMem::base = 0x60000000; // Address of SheepShaver data
331     uintptr SheepMem::top = 0; // Top of SheepShaver data (stack like storage)
332    
333 cebix 1.1
334     // Prototypes
335     static void Quit(void);
336     static void *emul_func(void *arg);
337     static void *nvram_func(void *arg);
338     static void *tick_func(void *arg);
339 gbeauche 1.8 #if EMULATED_PPC
340 gbeauche 1.13 extern void emul_ppc(uint32 start);
341     extern void init_emul_ppc(void);
342     extern void exit_emul_ppc(void);
343 gbeauche 1.43 sigsegv_return_t sigsegv_handler(sigsegv_address_t, sigsegv_address_t);
344 gbeauche 1.8 #else
345 gbeauche 1.26 static void sigusr2_handler(int sig, siginfo_t *sip, void *scp);
346     static void sigsegv_handler(int sig, siginfo_t *sip, void *scp);
347     static void sigill_handler(int sig, siginfo_t *sip, void *scp);
348 cebix 1.1 #endif
349    
350    
351     // From asm_linux.S
352 gbeauche 1.12 #if !EMULATED_PPC
353 cebix 1.1 extern "C" void *get_toc(void);
354     extern "C" void *get_sp(void);
355     extern "C" void flush_icache_range(void *start, void *end);
356     extern "C" void jump_to_rom(uint32 entry, uint32 context);
357     extern "C" void quit_emulator(void);
358     extern "C" void execute_68k(uint32 pc, M68kRegisters *r);
359     extern "C" void ppc_interrupt(uint32 entry, uint32 kernel_data);
360     extern "C" int atomic_add(int *var, int v);
361     extern "C" int atomic_and(int *var, int v);
362     extern "C" int atomic_or(int *var, int v);
363     extern void paranoia_check(void);
364 gbeauche 1.12 #endif
365    
366    
367     #if EMULATED_PPC
368     /*
369 gbeauche 1.20 * Return signal stack base
370     */
371    
372     uintptr SignalStackBase(void)
373     {
374     return sig_stack + SIG_STACK_SIZE;
375     }
376    
377    
378     /*
379 gbeauche 1.12 * Atomic operations
380     */
381    
382     #if HAVE_SPINLOCKS
383     static spinlock_t atomic_ops_lock = SPIN_LOCK_UNLOCKED;
384     #else
385     #define spin_lock(LOCK)
386     #define spin_unlock(LOCK)
387     #endif
388    
389     int atomic_add(int *var, int v)
390     {
391     spin_lock(&atomic_ops_lock);
392     int ret = *var;
393     *var += v;
394     spin_unlock(&atomic_ops_lock);
395     return ret;
396     }
397    
398     int atomic_and(int *var, int v)
399     {
400     spin_lock(&atomic_ops_lock);
401     int ret = *var;
402     *var &= v;
403     spin_unlock(&atomic_ops_lock);
404     return ret;
405     }
406    
407     int atomic_or(int *var, int v)
408     {
409     spin_lock(&atomic_ops_lock);
410     int ret = *var;
411     *var |= v;
412     spin_unlock(&atomic_ops_lock);
413     return ret;
414     }
415 cebix 1.1 #endif
416    
417    
418     /*
419     * Main program
420     */
421    
422     static void usage(const char *prg_name)
423     {
424     printf("Usage: %s [OPTION...]\n", prg_name);
425     printf("\nUnix options:\n");
426     printf(" --display STRING\n X display to use\n");
427     PrefsPrintUsage();
428     exit(0);
429     }
430    
431     int main(int argc, char **argv)
432     {
433     char str[256];
434     uint32 *boot_globs;
435     int16 i16;
436     int rom_fd;
437     FILE *proc_file;
438     const char *rom_path;
439     uint32 rom_size, actual;
440     uint8 *rom_tmp;
441     time_t now, expire;
442    
443     // Initialize variables
444     RAMBase = 0;
445     tzset();
446    
447     // Print some info
448     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
449     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
450    
451     #if !EMULATED_PPC
452     // Get TOC pointer
453     TOC = get_toc();
454     #endif
455    
456     #ifdef ENABLE_GTK
457     // Init GTK
458     gtk_set_locale();
459     gtk_init(&argc, &argv);
460     #endif
461    
462     // Read preferences
463     PrefsInit(argc, argv);
464    
465     // Parse command line arguments
466     for (int i=1; i<argc; i++) {
467     if (strcmp(argv[i], "--help") == 0) {
468     usage(argv[0]);
469 gbeauche 1.42 #ifndef USE_SDL_VIDEO
470 cebix 1.1 } else if (strcmp(argv[i], "--display") == 0) {
471     i++;
472     if (i < argc)
473     x_display_name = strdup(argv[i]);
474 gbeauche 1.42 #endif
475 cebix 1.1 } else if (argv[i][0] == '-') {
476     fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
477     usage(argv[0]);
478     }
479     }
480    
481 gbeauche 1.42 #ifdef USE_SDL
482     // Initialize SDL system
483     int sdl_flags = 0;
484     #ifdef USE_SDL_VIDEO
485     sdl_flags |= SDL_INIT_VIDEO;
486     #endif
487 gbeauche 1.51 #ifdef USE_SDL_AUDIO
488     sdl_flags |= SDL_INIT_AUDIO;
489     #endif
490 gbeauche 1.42 assert(sdl_flags != 0);
491     if (SDL_Init(sdl_flags) == -1) {
492     char str[256];
493     sprintf(str, "Could not initialize SDL: %s.\n", SDL_GetError());
494     ErrorAlert(str);
495     goto quit;
496     }
497     atexit(SDL_Quit);
498     #endif
499    
500     #ifndef USE_SDL_VIDEO
501 cebix 1.1 // Open display
502     x_display = XOpenDisplay(x_display_name);
503     if (x_display == NULL) {
504     char str[256];
505     sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
506     ErrorAlert(str);
507     goto quit;
508     }
509    
510     #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
511     // Fork out, so we can return from fullscreen mode when things get ugly
512     XF86DGAForkApp(DefaultScreen(x_display));
513     #endif
514 gbeauche 1.42 #endif
515 cebix 1.1
516     #ifdef ENABLE_MON
517     // Initialize mon
518     mon_init();
519     #endif
520    
521 gbeauche 1.43 #if !EMULATED_PPC
522 gbeauche 1.44 // Create and install stacks for signal handlers
523     for (int i = 0; i < SIG_STACK_COUNT; i++) {
524     void *sig_stack = malloc(SIG_STACK_SIZE);
525     D(bug("Signal stack %d at %p\n", i, sig_stack));
526     if (sig_stack == NULL) {
527     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
528     goto quit;
529     }
530     sig_stacks[i].ss_sp = sig_stack;
531     sig_stacks[i].ss_flags = 0;
532     sig_stacks[i].ss_size = SIG_STACK_SIZE;
533     }
534     sig_stack_id = 0;
535     if (sigaltstack(&sig_stacks[0], NULL) < 0) {
536     sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
537     ErrorAlert(str);
538     goto quit;
539     }
540     #endif
541    
542     #if !EMULATED_PPC
543 gbeauche 1.43 // Install SIGSEGV and SIGBUS handlers
544     sigemptyset(&sigsegv_action.sa_mask); // Block interrupts during SEGV handling
545     sigaddset(&sigsegv_action.sa_mask, SIGUSR2);
546     sigsegv_action.sa_sigaction = sigsegv_handler;
547     sigsegv_action.sa_flags = SA_ONSTACK | SA_SIGINFO;
548     #ifdef HAVE_SIGNAL_SA_RESTORER
549     sigsegv_action.sa_restorer = NULL;
550     #endif
551     if (sigaction(SIGSEGV, &sigsegv_action, NULL) < 0) {
552     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
553     ErrorAlert(str);
554     goto quit;
555     }
556     if (sigaction(SIGBUS, &sigsegv_action, NULL) < 0) {
557     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
558     ErrorAlert(str);
559     goto quit;
560     }
561     #else
562     // Install SIGSEGV handler for CPU emulator
563     if (!sigsegv_install_handler(sigsegv_handler)) {
564     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
565     ErrorAlert(str);
566     goto quit;
567     }
568     #endif
569    
570     // Initialize VM system
571     vm_init();
572    
573 cebix 1.1 // Get system info
574     PVR = 0x00040000; // Default: 604
575     CPUClockSpeed = 100000000; // Default: 100MHz
576     BusClockSpeed = 100000000; // Default: 100MHz
577 gbeauche 1.47 TimebaseSpeed = 25000000; // Default: 25MHz
578 gbeauche 1.30 #if EMULATED_PPC
579     PVR = 0x000c0000; // Default: 7400 (with AltiVec)
580 gbeauche 1.39 #elif defined(__APPLE__) && defined(__MACH__)
581     proc_file = popen("ioreg -c IOPlatformDevice", "r");
582     if (proc_file) {
583     char line[256];
584     bool powerpc_node = false;
585     while (fgets(line, sizeof(line) - 1, proc_file)) {
586     // Read line
587     int len = strlen(line);
588     if (len == 0)
589     continue;
590     line[len - 1] = 0;
591    
592     // Parse line
593     if (strstr(line, "o PowerPC,"))
594     powerpc_node = true;
595     else if (powerpc_node) {
596     uint32 value;
597     char head[256];
598     if (sscanf(line, "%[ |]\"cpu-version\" = <%x>", head, &value) == 2)
599     PVR = value;
600     else if (sscanf(line, "%[ |]\"clock-frequency\" = <%x>", head, &value) == 2)
601     CPUClockSpeed = value;
602     else if (sscanf(line, "%[ |]\"bus-frequency\" = <%x>", head, &value) == 2)
603     BusClockSpeed = value;
604 gbeauche 1.48 else if (sscanf(line, "%[ |]\"timebase-frequency\" = <%x>", head, &value) == 2)
605     TimebaseSpeed = value;
606 gbeauche 1.39 else if (strchr(line, '}'))
607     powerpc_node = false;
608     }
609     }
610     fclose(proc_file);
611     } else {
612     sprintf(str, GetString(STR_PROC_CPUINFO_WARN), strerror(errno));
613     WarningAlert(str);
614     }
615 gbeauche 1.30 #else
616 cebix 1.1 proc_file = fopen("/proc/cpuinfo", "r");
617     if (proc_file) {
618 gbeauche 1.50 // CPU specs from Linux kernel
619     // TODO: make it more generic with features (e.g. AltiVec) and
620     // cache information and friends for NameRegistry
621     static const struct {
622     uint32 pvr_mask;
623     uint32 pvr_value;
624     const char *cpu_name;
625     }
626     cpu_specs[] = {
627     { 0xffff0000, 0x00010000, "601" },
628     { 0xffff0000, 0x00030000, "603" },
629     { 0xffff0000, 0x00060000, "603e" },
630     { 0xffff0000, 0x00070000, "603ev" },
631     { 0xffff0000, 0x00040000, "604" },
632     { 0xfffff000, 0x00090000, "604e" },
633     { 0xffff0000, 0x00090000, "604r" },
634     { 0xffff0000, 0x000a0000, "604ev" },
635     { 0xffffffff, 0x00084202, "740/750" },
636     { 0xfffff000, 0x00083000, "745/755" },
637     { 0xfffffff0, 0x00080100, "750CX" },
638     { 0xfffffff0, 0x00082200, "750CX" },
639     { 0xfffffff0, 0x00082210, "750CXe" },
640     { 0xffffff00, 0x70000100, "750FX" },
641     { 0xffffffff, 0x70000200, "750FX" },
642     { 0xffff0000, 0x70000000, "750FX" },
643     { 0xffff0000, 0x70020000, "750GX" },
644     { 0xffff0000, 0x00080000, "740/750" },
645     { 0xffffffff, 0x000c1101, "7400 (1.1)" },
646     { 0xffff0000, 0x000c0000, "7400" },
647     { 0xffff0000, 0x800c0000, "7410" },
648     { 0xffffffff, 0x80000200, "7450" },
649     { 0xffffffff, 0x80000201, "7450" },
650     { 0xffff0000, 0x80000000, "7450" },
651     { 0xffffff00, 0x80010100, "7455" },
652     { 0xffffffff, 0x80010200, "7455" },
653     { 0xffff0000, 0x80010000, "7455" },
654     { 0xffff0000, 0x80020000, "7457" },
655     { 0xffff0000, 0x80030000, "7447A" },
656     { 0x7fff0000, 0x00810000, "82xx" },
657     { 0x7fff0000, 0x00820000, "8280" },
658     { 0xffff0000, 0x00400000, "Power3 (630)" },
659     { 0xffff0000, 0x00410000, "Power3 (630+)" },
660     { 0xffff0000, 0x00360000, "I-star" },
661     { 0xffff0000, 0x00370000, "S-star" },
662     { 0xffff0000, 0x00350000, "Power4" },
663     { 0xffff0000, 0x00390000, "PPC970" },
664     { 0, 0, 0 }
665     };
666    
667 cebix 1.1 char line[256];
668     while(fgets(line, 255, proc_file)) {
669     // Read line
670     int len = strlen(line);
671     if (len == 0)
672     continue;
673     line[len-1] = 0;
674    
675     // Parse line
676     int i;
677     char value[256];
678 gbeauche 1.29 if (sscanf(line, "cpu : %[0-9A-Za-a]", value) == 1) {
679 gbeauche 1.50 // Search by name
680     const char *cpu_name = NULL;
681     for (int i = 0; cpu_specs[i].pvr_mask != 0; i++) {
682     if (strcmp(cpu_specs[i].cpu_name, value) == 0) {
683     cpu_name = cpu_specs[i].cpu_name;
684     PVR = cpu_specs[i].pvr_value;
685     break;
686     }
687     }
688     if (cpu_name == NULL)
689     printf("WARNING: Unknown CPU type '%s', assuming 604\n", value);
690 cebix 1.1 else
691 gbeauche 1.50 printf("Found a PowerPC %s processor\n", cpu_name);
692 cebix 1.1 }
693     if (sscanf(line, "clock : %dMHz", &i) == 1)
694     CPUClockSpeed = BusClockSpeed = i * 1000000;
695     }
696     fclose(proc_file);
697     } else {
698     sprintf(str, GetString(STR_PROC_CPUINFO_WARN), strerror(errno));
699     WarningAlert(str);
700     }
701 gbeauche 1.34
702     // Get actual bus frequency
703     proc_file = fopen("/proc/device-tree/clock-frequency", "r");
704     if (proc_file) {
705     union { uint8 b[4]; uint32 l; } value;
706     if (fread(value.b, sizeof(value), 1, proc_file) == 1)
707     BusClockSpeed = value.l;
708     fclose(proc_file);
709     }
710 gbeauche 1.47
711     // Get actual timebase frequency
712     TimebaseSpeed = BusClockSpeed / 4;
713     DIR *cpus_dir;
714     if ((cpus_dir = opendir("/proc/device-tree/cpus")) != NULL) {
715     struct dirent *cpu_entry;
716     while ((cpu_entry = readdir(cpus_dir)) != NULL) {
717     if (strstr(cpu_entry->d_name, "PowerPC,") == cpu_entry->d_name) {
718     char timebase_freq_node[256];
719     sprintf(timebase_freq_node, "/proc/device-tree/cpus/%s/timebase-frequency", cpu_entry->d_name);
720     proc_file = fopen(timebase_freq_node, "r");
721     if (proc_file) {
722     union { uint8 b[4]; uint32 l; } value;
723     if (fread(value.b, sizeof(value), 1, proc_file) == 1)
724     TimebaseSpeed = value.l;
725     fclose(proc_file);
726     }
727     }
728     }
729     closedir(cpus_dir);
730     }
731 cebix 1.1 #endif
732 gbeauche 1.49 // Remap any newer G4/G5 processor to plain G4 for compatibility
733     switch (PVR >> 16) {
734     case 0x8000: // 7450
735     case 0x8001: // 7455
736     case 0x8002: // 7457
737     case 0x0039: // 970
738     PVR = 0x000c0000; // 7400
739     break;
740     }
741 cebix 1.1 D(bug("PVR: %08x (assumed)\n", PVR));
742    
743     // Init system routines
744     SysInit();
745    
746     // Show preferences editor
747     if (!PrefsFindBool("nogui"))
748     if (!PrefsEditor())
749     goto quit;
750    
751     #if !EMULATED_PPC
752     // Check some things
753     paranoia_check();
754     #endif
755    
756     // Open /dev/zero
757     zero_fd = open("/dev/zero", O_RDWR);
758     if (zero_fd < 0) {
759     sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
760     ErrorAlert(str);
761     goto quit;
762     }
763    
764 gbeauche 1.26 #ifndef PAGEZERO_HACK
765 cebix 1.1 // Create Low Memory area (0x0000..0x3000)
766 gbeauche 1.4 if (vm_acquire_fixed((char *)0, 0x3000) < 0) {
767 cebix 1.1 sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
768     ErrorAlert(str);
769     goto quit;
770     }
771     lm_area_mapped = true;
772 gbeauche 1.26 #endif
773 cebix 1.1
774     // Create areas for Kernel Data
775     kernel_area = shmget(IPC_PRIVATE, KERNEL_AREA_SIZE, 0600);
776     if (kernel_area == -1) {
777     sprintf(str, GetString(STR_KD_SHMGET_ERR), strerror(errno));
778     ErrorAlert(str);
779     goto quit;
780     }
781     if (shmat(kernel_area, (void *)KERNEL_DATA_BASE, 0) < 0) {
782     sprintf(str, GetString(STR_KD_SHMAT_ERR), strerror(errno));
783     ErrorAlert(str);
784     goto quit;
785     }
786     if (shmat(kernel_area, (void *)KERNEL_DATA2_BASE, 0) < 0) {
787     sprintf(str, GetString(STR_KD2_SHMAT_ERR), strerror(errno));
788     ErrorAlert(str);
789     goto quit;
790     }
791 gbeauche 1.15 kernel_data = (KernelData *)KERNEL_DATA_BASE;
792 cebix 1.1 emulator_data = &kernel_data->ed;
793 gbeauche 1.15 KernelDataAddr = KERNEL_DATA_BASE;
794 cebix 1.1 D(bug("Kernel Data at %p, Emulator Data at %p\n", kernel_data, emulator_data));
795    
796 gbeauche 1.36 // Create area for DR Cache
797     if (vm_acquire_fixed((void *)DR_EMULATOR_BASE, DR_EMULATOR_SIZE) < 0) {
798     sprintf(str, GetString(STR_DR_EMULATOR_MMAP_ERR), strerror(errno));
799     ErrorAlert(str);
800     goto quit;
801     }
802     dr_emulator_area_mapped = true;
803     if (vm_acquire_fixed((void *)DR_CACHE_BASE, DR_CACHE_SIZE) < 0) {
804     sprintf(str, GetString(STR_DR_CACHE_MMAP_ERR), strerror(errno));
805     ErrorAlert(str);
806     goto quit;
807     }
808     dr_cache_area_mapped = true;
809 gbeauche 1.38 #if !EMULATED_PPC
810     if (vm_protect((char *)DR_CACHE_BASE, DR_CACHE_SIZE, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
811     sprintf(str, GetString(STR_DR_CACHE_MMAP_ERR), strerror(errno));
812     ErrorAlert(str);
813     goto quit;
814     }
815     #endif
816 gbeauche 1.36 DRCacheAddr = DR_CACHE_BASE;
817     D(bug("DR Cache at %p\n", DRCacheAddr));
818    
819 gbeauche 1.8 // Create area for SheepShaver data
820 gbeauche 1.15 if (!SheepMem::Init()) {
821 gbeauche 1.8 sprintf(str, GetString(STR_SHEEP_MEM_MMAP_ERR), strerror(errno));
822     ErrorAlert(str);
823     goto quit;
824     }
825    
826 cebix 1.1 // Create area for Mac ROM
827 gbeauche 1.4 if (vm_acquire_fixed((char *)ROM_BASE, ROM_AREA_SIZE) < 0) {
828 cebix 1.1 sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
829     ErrorAlert(str);
830     goto quit;
831     }
832 gbeauche 1.27 #if !EMULATED_PPC
833 gbeauche 1.4 if (vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
834     sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
835     ErrorAlert(str);
836     goto quit;
837     }
838     #endif
839 cebix 1.1 rom_area_mapped = true;
840     D(bug("ROM area at %08x\n", ROM_BASE));
841    
842     // Create area for Mac RAM
843     RAMSize = PrefsFindInt32("ramsize");
844     if (RAMSize < 8*1024*1024) {
845     WarningAlert(GetString(STR_SMALL_RAM_WARN));
846     RAMSize = 8*1024*1024;
847     }
848    
849 gbeauche 1.8 if (vm_acquire_fixed((char *)RAM_BASE, RAMSize) < 0) {
850 cebix 1.1 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
851     ErrorAlert(str);
852     goto quit;
853     }
854 gbeauche 1.4 #if !EMULATED_PPC
855 gbeauche 1.8 if (vm_protect((char *)RAM_BASE, RAMSize, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
856 gbeauche 1.4 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
857     ErrorAlert(str);
858     goto quit;
859     }
860     #endif
861 gbeauche 1.8 RAMBase = RAM_BASE;
862 cebix 1.1 ram_area_mapped = true;
863     D(bug("RAM area at %08x\n", RAMBase));
864    
865     if (RAMBase > ROM_BASE) {
866     ErrorAlert(GetString(STR_RAM_HIGHER_THAN_ROM_ERR));
867     goto quit;
868     }
869    
870     // Load Mac ROM
871     rom_path = PrefsFindString("rom");
872     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
873     if (rom_fd < 0) {
874     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME2, O_RDONLY);
875     if (rom_fd < 0) {
876     ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
877     goto quit;
878     }
879     }
880     printf(GetString(STR_READING_ROM_FILE));
881     rom_size = lseek(rom_fd, 0, SEEK_END);
882     lseek(rom_fd, 0, SEEK_SET);
883     rom_tmp = new uint8[ROM_SIZE];
884     actual = read(rom_fd, (void *)rom_tmp, ROM_SIZE);
885     close(rom_fd);
886 gbeauche 1.3
887     // Decode Mac ROM
888     if (!DecodeROM(rom_tmp, actual)) {
889     if (rom_size != 4*1024*1024) {
890 cebix 1.1 ErrorAlert(GetString(STR_ROM_SIZE_ERR));
891     goto quit;
892     } else {
893     ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
894     goto quit;
895     }
896     }
897 gbeauche 1.3 delete[] rom_tmp;
898 cebix 1.1
899     // Load NVRAM
900     XPRAMInit();
901    
902 gbeauche 1.32 // Load XPRAM default values if signature not found
903     if (XPRAM[0x130c] != 0x4e || XPRAM[0x130d] != 0x75
904     || XPRAM[0x130e] != 0x4d || XPRAM[0x130f] != 0x63) {
905     D(bug("Loading XPRAM default values\n"));
906     memset(XPRAM + 0x1300, 0, 0x100);
907     XPRAM[0x130c] = 0x4e; // "NuMc" signature
908     XPRAM[0x130d] = 0x75;
909     XPRAM[0x130e] = 0x4d;
910     XPRAM[0x130f] = 0x63;
911     XPRAM[0x1301] = 0x80; // InternalWaitFlags = DynWait (don't wait for SCSI devices upon bootup)
912     XPRAM[0x1310] = 0xa8; // Standard PRAM values
913     XPRAM[0x1311] = 0x00;
914     XPRAM[0x1312] = 0x00;
915     XPRAM[0x1313] = 0x22;
916     XPRAM[0x1314] = 0xcc;
917     XPRAM[0x1315] = 0x0a;
918     XPRAM[0x1316] = 0xcc;
919     XPRAM[0x1317] = 0x0a;
920     XPRAM[0x131c] = 0x00;
921     XPRAM[0x131d] = 0x02;
922     XPRAM[0x131e] = 0x63;
923     XPRAM[0x131f] = 0x00;
924     XPRAM[0x1308] = 0x13;
925     XPRAM[0x1309] = 0x88;
926     XPRAM[0x130a] = 0x00;
927     XPRAM[0x130b] = 0xcc;
928     XPRAM[0x1376] = 0x00; // OSDefault = MacOS
929     XPRAM[0x1377] = 0x01;
930     }
931    
932 cebix 1.1 // Set boot volume
933 cebix 1.10 i16 = PrefsFindInt32("bootdrive");
934 cebix 1.1 XPRAM[0x1378] = i16 >> 8;
935     XPRAM[0x1379] = i16 & 0xff;
936 cebix 1.10 i16 = PrefsFindInt32("bootdriver");
937 cebix 1.1 XPRAM[0x137a] = i16 >> 8;
938     XPRAM[0x137b] = i16 & 0xff;
939    
940     // Create BootGlobs at top of Mac memory
941     memset((void *)(RAMBase + RAMSize - 4096), 0, 4096);
942     BootGlobsAddr = RAMBase + RAMSize - 0x1c;
943     boot_globs = (uint32 *)BootGlobsAddr;
944     boot_globs[-5] = htonl(RAMBase + RAMSize); // MemTop
945     boot_globs[0] = htonl(RAMBase); // First RAM bank
946     boot_globs[1] = htonl(RAMSize);
947     boot_globs[2] = htonl((uint32)-1); // End of bank table
948    
949 gbeauche 1.15 // Init thunks
950     if (!ThunksInit())
951     goto quit;
952    
953 cebix 1.1 // Init drivers
954     SonyInit();
955     DiskInit();
956     CDROMInit();
957     SCSIInit();
958    
959     // Init external file system
960     ExtFSInit();
961    
962 gbeauche 1.22 // Init ADB
963     ADBInit();
964    
965 cebix 1.1 // Init audio
966     AudioInit();
967    
968     // Init network
969     EtherInit();
970    
971     // Init serial ports
972     SerialInit();
973    
974     // Init Time Manager
975     TimerInit();
976    
977     // Init clipboard
978     ClipInit();
979    
980     // Init video
981     if (!VideoInit())
982     goto quit;
983    
984     // Install ROM patches
985     if (!PatchROM()) {
986     ErrorAlert(GetString(STR_UNSUPPORTED_ROM_TYPE_ERR));
987     goto quit;
988     }
989    
990     // Clear caches (as we loaded and patched code) and write protect ROM
991     #if !EMULATED_PPC
992     MakeExecutable(0, (void *)ROM_BASE, ROM_AREA_SIZE);
993     #endif
994 gbeauche 1.4 vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_EXECUTE);
995 cebix 1.1
996     // Initialize Kernel Data
997     memset(kernel_data, 0, sizeof(KernelData));
998     if (ROMType == ROMTYPE_NEWWORLD) {
999 gbeauche 1.15 uintptr of_dev_tree = SheepMem::Reserve(4 * sizeof(uint32));
1000     memset((void *)of_dev_tree, 0, 4 * sizeof(uint32));
1001     uintptr vector_lookup_tbl = SheepMem::Reserve(128);
1002     uintptr vector_mask_tbl = SheepMem::Reserve(64);
1003 cebix 1.1 memset((uint8 *)kernel_data + 0xb80, 0x3d, 0x80);
1004 gbeauche 1.15 memset((void *)vector_lookup_tbl, 0, 128);
1005     memset((void *)vector_mask_tbl, 0, 64);
1006 cebix 1.1 kernel_data->v[0xb80 >> 2] = htonl(ROM_BASE);
1007 gbeauche 1.15 kernel_data->v[0xb84 >> 2] = htonl(of_dev_tree); // OF device tree base
1008     kernel_data->v[0xb90 >> 2] = htonl(vector_lookup_tbl);
1009     kernel_data->v[0xb94 >> 2] = htonl(vector_mask_tbl);
1010 cebix 1.1 kernel_data->v[0xb98 >> 2] = htonl(ROM_BASE); // OpenPIC base
1011     kernel_data->v[0xbb0 >> 2] = htonl(0); // ADB base
1012     kernel_data->v[0xc20 >> 2] = htonl(RAMSize);
1013     kernel_data->v[0xc24 >> 2] = htonl(RAMSize);
1014     kernel_data->v[0xc30 >> 2] = htonl(RAMSize);
1015     kernel_data->v[0xc34 >> 2] = htonl(RAMSize);
1016     kernel_data->v[0xc38 >> 2] = htonl(0x00010020);
1017     kernel_data->v[0xc3c >> 2] = htonl(0x00200001);
1018     kernel_data->v[0xc40 >> 2] = htonl(0x00010000);
1019     kernel_data->v[0xc50 >> 2] = htonl(RAMBase);
1020     kernel_data->v[0xc54 >> 2] = htonl(RAMSize);
1021     kernel_data->v[0xf60 >> 2] = htonl(PVR);
1022 gbeauche 1.34 kernel_data->v[0xf64 >> 2] = htonl(CPUClockSpeed); // clock-frequency
1023     kernel_data->v[0xf68 >> 2] = htonl(BusClockSpeed); // bus-frequency
1024 gbeauche 1.47 kernel_data->v[0xf6c >> 2] = htonl(TimebaseSpeed); // timebase-frequency
1025 cebix 1.1 } else {
1026     kernel_data->v[0xc80 >> 2] = htonl(RAMSize);
1027     kernel_data->v[0xc84 >> 2] = htonl(RAMSize);
1028     kernel_data->v[0xc90 >> 2] = htonl(RAMSize);
1029     kernel_data->v[0xc94 >> 2] = htonl(RAMSize);
1030     kernel_data->v[0xc98 >> 2] = htonl(0x00010020);
1031     kernel_data->v[0xc9c >> 2] = htonl(0x00200001);
1032     kernel_data->v[0xca0 >> 2] = htonl(0x00010000);
1033     kernel_data->v[0xcb0 >> 2] = htonl(RAMBase);
1034     kernel_data->v[0xcb4 >> 2] = htonl(RAMSize);
1035     kernel_data->v[0xf80 >> 2] = htonl(PVR);
1036 gbeauche 1.34 kernel_data->v[0xf84 >> 2] = htonl(CPUClockSpeed); // clock-frequency
1037     kernel_data->v[0xf88 >> 2] = htonl(BusClockSpeed); // bus-frequency
1038 gbeauche 1.47 kernel_data->v[0xf8c >> 2] = htonl(TimebaseSpeed); // timebase-frequency
1039 cebix 1.1 }
1040    
1041     // Initialize extra low memory
1042     D(bug("Initializing Low Memory...\n"));
1043     memset(NULL, 0, 0x3000);
1044     WriteMacInt32(XLM_SIGNATURE, FOURCC('B','a','a','h')); // Signature to detect SheepShaver
1045 gbeauche 1.15 WriteMacInt32(XLM_KERNEL_DATA, KernelDataAddr); // For trap replacement routines
1046 cebix 1.1 WriteMacInt32(XLM_PVR, PVR); // Theoretical PVR
1047     WriteMacInt32(XLM_BUS_CLOCK, BusClockSpeed); // For DriverServicesLib patch
1048     WriteMacInt16(XLM_EXEC_RETURN_OPCODE, M68K_EXEC_RETURN); // For Execute68k() (RTS from the executed 68k code will jump here and end 68k mode)
1049 gbeauche 1.18 WriteMacInt32(XLM_ZERO_PAGE, SheepMem::ZeroPage()); // Pointer to read-only page with all bits set to 0
1050 gbeauche 1.17 #if !EMULATED_PPC
1051     WriteMacInt32(XLM_TOC, (uint32)TOC); // TOC pointer of emulator
1052     #endif
1053     WriteMacInt32(XLM_ETHER_INIT, NativeFunction(NATIVE_ETHER_INIT)); // DLPI ethernet driver functions
1054 gbeauche 1.15 WriteMacInt32(XLM_ETHER_TERM, NativeFunction(NATIVE_ETHER_TERM));
1055     WriteMacInt32(XLM_ETHER_OPEN, NativeFunction(NATIVE_ETHER_OPEN));
1056     WriteMacInt32(XLM_ETHER_CLOSE, NativeFunction(NATIVE_ETHER_CLOSE));
1057     WriteMacInt32(XLM_ETHER_WPUT, NativeFunction(NATIVE_ETHER_WPUT));
1058     WriteMacInt32(XLM_ETHER_RSRV, NativeFunction(NATIVE_ETHER_RSRV));
1059     WriteMacInt32(XLM_VIDEO_DOIO, NativeFunction(NATIVE_VIDEO_DO_DRIVER_IO));
1060 cebix 1.1 D(bug("Low Memory initialized\n"));
1061    
1062     // Start 60Hz thread
1063 gbeauche 1.40 tick_thread_cancel = false;
1064 cebix 1.1 tick_thread_active = (pthread_create(&tick_thread, NULL, tick_func, NULL) == 0);
1065     D(bug("Tick thread installed (%ld)\n", tick_thread));
1066    
1067     // Start NVRAM watchdog thread
1068     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
1069 gbeauche 1.40 nvram_thread_cancel = false;
1070 cebix 1.1 nvram_thread_active = (pthread_create(&nvram_thread, NULL, nvram_func, NULL) == 0);
1071     D(bug("NVRAM thread installed (%ld)\n", nvram_thread));
1072    
1073     #if !EMULATED_PPC
1074     // Install SIGILL handler
1075     sigemptyset(&sigill_action.sa_mask); // Block interrupts during ILL handling
1076     sigaddset(&sigill_action.sa_mask, SIGUSR2);
1077 gbeauche 1.26 sigill_action.sa_sigaction = sigill_handler;
1078     sigill_action.sa_flags = SA_ONSTACK | SA_SIGINFO;
1079     #ifdef HAVE_SIGNAL_SA_RESTORER
1080 cebix 1.1 sigill_action.sa_restorer = NULL;
1081 gbeauche 1.26 #endif
1082 cebix 1.1 if (sigaction(SIGILL, &sigill_action, NULL) < 0) {
1083     sprintf(str, GetString(STR_SIGILL_INSTALL_ERR), strerror(errno));
1084     ErrorAlert(str);
1085     goto quit;
1086     }
1087 gbeauche 1.6 #endif
1088 cebix 1.1
1089 gbeauche 1.26 #if !EMULATED_PPC
1090 cebix 1.1 // Install interrupt signal handler
1091     sigemptyset(&sigusr2_action.sa_mask);
1092 gbeauche 1.26 sigusr2_action.sa_sigaction = sigusr2_handler;
1093     sigusr2_action.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
1094     #ifdef HAVE_SIGNAL_SA_RESTORER
1095     sigusr2_action.sa_restorer = NULL;
1096 gbeauche 1.8 #endif
1097 cebix 1.1 if (sigaction(SIGUSR2, &sigusr2_action, NULL) < 0) {
1098     sprintf(str, GetString(STR_SIGUSR2_INSTALL_ERR), strerror(errno));
1099     ErrorAlert(str);
1100     goto quit;
1101     }
1102 gbeauche 1.26 #endif
1103 cebix 1.1
1104     // Get my thread ID and execute MacOS thread function
1105     emul_thread = pthread_self();
1106     D(bug("MacOS thread is %ld\n", emul_thread));
1107     emul_func(NULL);
1108    
1109     quit:
1110     Quit();
1111     return 0;
1112     }
1113    
1114    
1115     /*
1116     * Cleanup and quit
1117     */
1118    
1119     static void Quit(void)
1120     {
1121 gbeauche 1.13 #if EMULATED_PPC
1122     // Exit PowerPC emulation
1123     exit_emul_ppc();
1124     #endif
1125    
1126 cebix 1.1 // Stop 60Hz thread
1127     if (tick_thread_active) {
1128 gbeauche 1.40 tick_thread_cancel = true;
1129 cebix 1.1 pthread_cancel(tick_thread);
1130     pthread_join(tick_thread, NULL);
1131     }
1132    
1133     // Stop NVRAM watchdog thread
1134     if (nvram_thread_active) {
1135 gbeauche 1.40 nvram_thread_cancel = true;
1136 cebix 1.1 pthread_cancel(nvram_thread);
1137     pthread_join(nvram_thread, NULL);
1138     }
1139    
1140     #if !EMULATED_PPC
1141 gbeauche 1.23 // Uninstall SIGSEGV and SIGBUS handlers
1142 cebix 1.1 sigemptyset(&sigsegv_action.sa_mask);
1143     sigsegv_action.sa_handler = SIG_DFL;
1144     sigsegv_action.sa_flags = 0;
1145     sigaction(SIGSEGV, &sigsegv_action, NULL);
1146 gbeauche 1.23 sigaction(SIGBUS, &sigsegv_action, NULL);
1147 cebix 1.1
1148     // Uninstall SIGILL handler
1149     sigemptyset(&sigill_action.sa_mask);
1150     sigill_action.sa_handler = SIG_DFL;
1151     sigill_action.sa_flags = 0;
1152     sigaction(SIGILL, &sigill_action, NULL);
1153 gbeauche 1.33
1154     // Delete stacks for signal handlers
1155     for (int i = 0; i < SIG_STACK_COUNT; i++) {
1156     void *sig_stack = sig_stacks[i].ss_sp;
1157     if (sig_stack)
1158     free(sig_stack);
1159     }
1160 cebix 1.1 #endif
1161    
1162     // Save NVRAM
1163     XPRAMExit();
1164    
1165     // Exit clipboard
1166     ClipExit();
1167    
1168     // Exit Time Manager
1169     TimerExit();
1170    
1171     // Exit serial
1172     SerialExit();
1173    
1174     // Exit network
1175     EtherExit();
1176    
1177     // Exit audio
1178     AudioExit();
1179 gbeauche 1.22
1180     // Exit ADB
1181     ADBExit();
1182 cebix 1.1
1183     // Exit video
1184     VideoExit();
1185    
1186     // Exit external file system
1187     ExtFSExit();
1188    
1189     // Exit drivers
1190     SCSIExit();
1191     CDROMExit();
1192     DiskExit();
1193     SonyExit();
1194    
1195 gbeauche 1.24 // Delete thunks
1196     ThunksExit();
1197    
1198 gbeauche 1.15 // Delete SheepShaver globals
1199     SheepMem::Exit();
1200    
1201 cebix 1.1 // Delete RAM area
1202     if (ram_area_mapped)
1203 gbeauche 1.8 vm_release((char *)RAM_BASE, RAMSize);
1204 cebix 1.1
1205     // Delete ROM area
1206     if (rom_area_mapped)
1207 gbeauche 1.4 vm_release((char *)ROM_BASE, ROM_AREA_SIZE);
1208 cebix 1.1
1209 gbeauche 1.36 // Delete DR cache areas
1210     if (dr_emulator_area_mapped)
1211     vm_release((void *)DR_EMULATOR_BASE, DR_EMULATOR_SIZE);
1212     if (dr_cache_area_mapped)
1213     vm_release((void *)DR_CACHE_BASE, DR_CACHE_SIZE);
1214    
1215 cebix 1.1 // Delete Kernel Data area
1216     if (kernel_area >= 0) {
1217     shmdt((void *)KERNEL_DATA_BASE);
1218     shmdt((void *)KERNEL_DATA2_BASE);
1219     shmctl(kernel_area, IPC_RMID, NULL);
1220     }
1221    
1222     // Delete Low Memory area
1223     if (lm_area_mapped)
1224     munmap((char *)0x0000, 0x3000);
1225    
1226     // Close /dev/zero
1227     if (zero_fd > 0)
1228     close(zero_fd);
1229    
1230     // Exit system routines
1231     SysExit();
1232    
1233     // Exit preferences
1234     PrefsExit();
1235    
1236     #ifdef ENABLE_MON
1237     // Exit mon
1238     mon_exit();
1239     #endif
1240    
1241     // Close X11 server connection
1242 gbeauche 1.42 #ifndef USE_SDL_VIDEO
1243 cebix 1.1 if (x_display)
1244     XCloseDisplay(x_display);
1245 gbeauche 1.42 #endif
1246 cebix 1.1
1247     exit(0);
1248     }
1249    
1250    
1251     /*
1252     * Jump into Mac ROM, start 680x0 emulator
1253     */
1254    
1255     #if EMULATED_PPC
1256     void jump_to_rom(uint32 entry)
1257     {
1258     init_emul_ppc();
1259     emul_ppc(entry);
1260     }
1261     #endif
1262    
1263    
1264     /*
1265     * Emulator thread function
1266     */
1267    
1268     static void *emul_func(void *arg)
1269     {
1270     // We're now ready to receive signals
1271     ready_for_signals = true;
1272    
1273     // Decrease priority, so more time-critical things like audio will work better
1274     nice(1);
1275    
1276     // Jump to ROM boot routine
1277     D(bug("Jumping to ROM\n"));
1278     #if EMULATED_PPC
1279     jump_to_rom(ROM_BASE + 0x310000);
1280     #else
1281     jump_to_rom(ROM_BASE + 0x310000, (uint32)emulator_data);
1282     #endif
1283     D(bug("Returned from ROM\n"));
1284    
1285     // We're no longer ready to receive signals
1286     ready_for_signals = false;
1287     return NULL;
1288     }
1289    
1290    
1291     #if !EMULATED_PPC
1292     /*
1293     * Execute 68k subroutine (must be ended with RTS)
1294     * This must only be called by the emul_thread when in EMUL_OP mode
1295     * r->a[7] is unused, the routine runs on the caller's stack
1296     */
1297    
1298     void Execute68k(uint32 pc, M68kRegisters *r)
1299     {
1300     #if SAFE_EXEC_68K
1301     if (ReadMacInt32(XLM_RUN_MODE) != MODE_EMUL_OP)
1302     printf("FATAL: Execute68k() not called from EMUL_OP mode\n");
1303     if (!pthread_equal(pthread_self(), emul_thread))
1304     printf("FATAL: Execute68k() not called from emul_thread\n");
1305     #endif
1306     execute_68k(pc, r);
1307     }
1308    
1309    
1310     /*
1311     * Execute 68k A-Trap from EMUL_OP routine
1312     * r->a[7] is unused, the routine runs on the caller's stack
1313     */
1314    
1315     void Execute68kTrap(uint16 trap, M68kRegisters *r)
1316     {
1317     uint16 proc[2] = {trap, M68K_RTS};
1318     Execute68k((uint32)proc, r);
1319     }
1320 gbeauche 1.7 #endif
1321 cebix 1.1
1322    
1323     /*
1324     * Quit emulator (cause return from jump_to_rom)
1325     */
1326    
1327     void QuitEmulator(void)
1328     {
1329     #if EMULATED_PPC
1330     Quit();
1331     #else
1332     quit_emulator();
1333     #endif
1334     }
1335    
1336    
1337     /*
1338     * Pause/resume emulator
1339     */
1340    
1341     void PauseEmulator(void)
1342     {
1343     pthread_kill(emul_thread, SIGSTOP);
1344     }
1345    
1346     void ResumeEmulator(void)
1347     {
1348     pthread_kill(emul_thread, SIGCONT);
1349     }
1350    
1351    
1352     /*
1353     * Dump 68k registers
1354     */
1355    
1356     void Dump68kRegs(M68kRegisters *r)
1357     {
1358     // Display 68k registers
1359     for (int i=0; i<8; i++) {
1360     printf("d%d: %08x", i, r->d[i]);
1361     if (i == 3 || i == 7)
1362     printf("\n");
1363     else
1364     printf(", ");
1365     }
1366     for (int i=0; i<8; i++) {
1367     printf("a%d: %08x", i, r->a[i]);
1368     if (i == 3 || i == 7)
1369     printf("\n");
1370     else
1371     printf(", ");
1372     }
1373     }
1374    
1375    
1376     /*
1377     * Make code executable
1378     */
1379    
1380     void MakeExecutable(int dummy, void *start, uint32 length)
1381     {
1382 gbeauche 1.9 if (((uintptr)start >= ROM_BASE) && ((uintptr)start < (ROM_BASE + ROM_SIZE)))
1383 cebix 1.1 return;
1384 gbeauche 1.9 #if EMULATED_PPC
1385     FlushCodeCache((uintptr)start, (uintptr)start + length);
1386     #else
1387     flush_icache_range(start, (void *)((uintptr)start + length));
1388 cebix 1.1 #endif
1389     }
1390    
1391    
1392     /*
1393     * Patch things after system startup (gets called by disk driver accRun routine)
1394     */
1395    
1396     void PatchAfterStartup(void)
1397     {
1398 gbeauche 1.6 ExecuteNative(NATIVE_VIDEO_INSTALL_ACCEL);
1399 cebix 1.1 InstallExtFS();
1400     }
1401    
1402    
1403     /*
1404     * NVRAM watchdog thread (saves NVRAM every minute)
1405     */
1406    
1407 gbeauche 1.40 static void nvram_watchdog(void)
1408     {
1409     if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
1410     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
1411     SaveXPRAM();
1412     }
1413     }
1414    
1415 cebix 1.1 static void *nvram_func(void *arg)
1416     {
1417 gbeauche 1.40 while (!nvram_thread_cancel) {
1418     for (int i=0; i<60 && !nvram_thread_cancel; i++)
1419     Delay_usec(999999); // Only wait 1 second so we quit promptly when nvram_thread_cancel becomes true
1420     nvram_watchdog();
1421 cebix 1.1 }
1422     return NULL;
1423     }
1424    
1425    
1426     /*
1427     * 60Hz thread (really 60.15Hz)
1428     */
1429    
1430     static void *tick_func(void *arg)
1431     {
1432     int tick_counter = 0;
1433 gbeauche 1.40 uint64 start = GetTicks_usec();
1434     int64 ticks = 0;
1435     uint64 next = GetTicks_usec();
1436 cebix 1.1
1437 gbeauche 1.40 while (!tick_thread_cancel) {
1438 cebix 1.1
1439     // Wait
1440 gbeauche 1.40 next += 16625;
1441     int64 delay = next - GetTicks_usec();
1442     if (delay > 0)
1443     Delay_usec(delay);
1444     else if (delay < -16625)
1445     next = GetTicks_usec();
1446     ticks++;
1447 cebix 1.1
1448     #if !EMULATED_PPC
1449     // Did we crash?
1450     if (emul_thread_fatal) {
1451    
1452     // Yes, dump registers
1453 gbeauche 1.26 sigregs *r = &sigsegv_regs;
1454 cebix 1.1 char str[256];
1455 gbeauche 1.23 if (crash_reason == NULL)
1456     crash_reason = "SIGSEGV";
1457     sprintf(str, "%s\n"
1458 cebix 1.1 " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1459     " xer %08lx cr %08lx \n"
1460     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1461     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1462     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1463     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1464     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1465     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1466     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1467     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1468 gbeauche 1.23 crash_reason,
1469 cebix 1.1 r->nip, r->link, r->ctr, r->msr,
1470     r->xer, r->ccr,
1471     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1472     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1473     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1474     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1475     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1476     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1477     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1478     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1479     printf(str);
1480     VideoQuitFullScreen();
1481    
1482     #ifdef ENABLE_MON
1483     // Start up mon in real-mode
1484     printf("Welcome to the sheep factory.\n");
1485     char *arg[4] = {"mon", "-m", "-r", NULL};
1486     mon(3, arg);
1487     #endif
1488     return NULL;
1489     }
1490     #endif
1491    
1492     // Pseudo Mac 1Hz interrupt, update local time
1493     if (++tick_counter > 60) {
1494     tick_counter = 0;
1495     WriteMacInt32(0x20c, TimerDateTime());
1496     }
1497    
1498     // Trigger 60Hz interrupt
1499     if (ReadMacInt32(XLM_IRQ_NEST) == 0) {
1500     SetInterruptFlag(INTFLAG_VIA);
1501     TriggerInterrupt();
1502     }
1503     }
1504 gbeauche 1.40
1505     uint64 end = GetTicks_usec();
1506     D(bug("%Ld ticks in %Ld usec = %f ticks/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
1507 cebix 1.1 return NULL;
1508     }
1509    
1510    
1511     /*
1512 cebix 1.2 * Pthread configuration
1513     */
1514    
1515     void Set_pthread_attr(pthread_attr_t *attr, int priority)
1516     {
1517 gbeauche 1.14 #ifdef HAVE_PTHREADS
1518     pthread_attr_init(attr);
1519     #if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
1520     // Some of these only work for superuser
1521     if (geteuid() == 0) {
1522     pthread_attr_setinheritsched(attr, PTHREAD_EXPLICIT_SCHED);
1523     pthread_attr_setschedpolicy(attr, SCHED_FIFO);
1524     struct sched_param fifo_param;
1525     fifo_param.sched_priority = ((sched_get_priority_min(SCHED_FIFO) +
1526     sched_get_priority_max(SCHED_FIFO)) / 2 +
1527     priority);
1528     pthread_attr_setschedparam(attr, &fifo_param);
1529     }
1530     if (pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM) != 0) {
1531     #ifdef PTHREAD_SCOPE_BOUND_NP
1532     // If system scope is not available (eg. we're not running
1533     // with CAP_SCHED_MGT capability on an SGI box), try bound
1534     // scope. It exposes pthread scheduling to the kernel,
1535     // without setting realtime priority.
1536     pthread_attr_setscope(attr, PTHREAD_SCOPE_BOUND_NP);
1537     #endif
1538     }
1539     #endif
1540     #endif
1541 cebix 1.2 }
1542    
1543    
1544     /*
1545 cebix 1.1 * Mutexes
1546     */
1547    
1548 gbeauche 1.7 #ifdef HAVE_PTHREADS
1549    
1550     struct B2_mutex {
1551     B2_mutex() {
1552     pthread_mutexattr_t attr;
1553     pthread_mutexattr_init(&attr);
1554     // Initialize the mutex for priority inheritance --
1555     // required for accurate timing.
1556     #ifdef HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL
1557     pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
1558     #endif
1559     #if defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE) && defined(PTHREAD_MUTEX_NORMAL)
1560     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
1561     #endif
1562     #ifdef HAVE_PTHREAD_MUTEXATTR_SETPSHARED
1563     pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);
1564     #endif
1565     pthread_mutex_init(&m, &attr);
1566     pthread_mutexattr_destroy(&attr);
1567     }
1568     ~B2_mutex() {
1569     pthread_mutex_trylock(&m); // Make sure it's locked before
1570     pthread_mutex_unlock(&m); // unlocking it.
1571     pthread_mutex_destroy(&m);
1572     }
1573     pthread_mutex_t m;
1574     };
1575    
1576     B2_mutex *B2_create_mutex(void)
1577     {
1578     return new B2_mutex;
1579     }
1580    
1581     void B2_lock_mutex(B2_mutex *mutex)
1582     {
1583     pthread_mutex_lock(&mutex->m);
1584     }
1585    
1586     void B2_unlock_mutex(B2_mutex *mutex)
1587     {
1588     pthread_mutex_unlock(&mutex->m);
1589     }
1590    
1591     void B2_delete_mutex(B2_mutex *mutex)
1592     {
1593     delete mutex;
1594     }
1595    
1596     #else
1597    
1598 cebix 1.1 struct B2_mutex {
1599     int dummy;
1600     };
1601    
1602     B2_mutex *B2_create_mutex(void)
1603     {
1604     return new B2_mutex;
1605     }
1606    
1607     void B2_lock_mutex(B2_mutex *mutex)
1608     {
1609     }
1610    
1611     void B2_unlock_mutex(B2_mutex *mutex)
1612     {
1613     }
1614    
1615     void B2_delete_mutex(B2_mutex *mutex)
1616     {
1617     delete mutex;
1618     }
1619    
1620 gbeauche 1.7 #endif
1621    
1622 cebix 1.1
1623     /*
1624     * Trigger signal USR2 from another thread
1625     */
1626    
1627 gbeauche 1.35 #if !EMULATED_PPC
1628 cebix 1.1 void TriggerInterrupt(void)
1629     {
1630     if (ready_for_signals)
1631     pthread_kill(emul_thread, SIGUSR2);
1632     }
1633 gbeauche 1.7 #endif
1634 cebix 1.1
1635    
1636     /*
1637     * Interrupt flags (must be handled atomically!)
1638     */
1639    
1640     volatile uint32 InterruptFlags = 0;
1641    
1642     void SetInterruptFlag(uint32 flag)
1643     {
1644     atomic_or((int *)&InterruptFlags, flag);
1645     }
1646    
1647     void ClearInterruptFlag(uint32 flag)
1648     {
1649     atomic_and((int *)&InterruptFlags, ~flag);
1650     }
1651    
1652    
1653     /*
1654     * Disable interrupts
1655     */
1656    
1657     void DisableInterrupt(void)
1658     {
1659 gbeauche 1.41 #if EMULATED_PPC
1660     WriteMacInt32(XLM_IRQ_NEST, int32(ReadMacInt32(XLM_IRQ_NEST)) + 1);
1661     #else
1662 gbeauche 1.7 atomic_add((int *)XLM_IRQ_NEST, 1);
1663 gbeauche 1.41 #endif
1664 cebix 1.1 }
1665    
1666    
1667     /*
1668     * Enable interrupts
1669     */
1670    
1671     void EnableInterrupt(void)
1672     {
1673 gbeauche 1.41 #if EMULATED_PPC
1674     WriteMacInt32(XLM_IRQ_NEST, int32(ReadMacInt32(XLM_IRQ_NEST)) - 1);
1675     #else
1676 gbeauche 1.7 atomic_add((int *)XLM_IRQ_NEST, -1);
1677 gbeauche 1.41 #endif
1678 cebix 1.1 }
1679    
1680    
1681     /*
1682     * USR2 handler
1683     */
1684    
1685 gbeauche 1.35 #if !EMULATED_PPC
1686 gbeauche 1.26 static void sigusr2_handler(int sig, siginfo_t *sip, void *scp)
1687 cebix 1.1 {
1688 gbeauche 1.26 machine_regs *r = MACHINE_REGISTERS(scp);
1689 cebix 1.1
1690 gbeauche 1.42 #ifdef USE_SDL_VIDEO
1691     // We must fill in the events queue in the same thread that did call SDL_SetVideoMode()
1692     SDL_PumpEvents();
1693     #endif
1694    
1695 cebix 1.1 // Do nothing if interrupts are disabled
1696     if (*(int32 *)XLM_IRQ_NEST > 0)
1697     return;
1698    
1699     // Disable MacOS stack sniffer
1700     WriteMacInt32(0x110, 0);
1701    
1702     // Interrupt action depends on current run mode
1703     switch (ReadMacInt32(XLM_RUN_MODE)) {
1704     case MODE_68K:
1705     // 68k emulator active, trigger 68k interrupt level 1
1706     WriteMacInt16(ntohl(kernel_data->v[0x67c >> 2]), 1);
1707 gbeauche 1.26 r->cr() |= ntohl(kernel_data->v[0x674 >> 2]);
1708 cebix 1.1 break;
1709    
1710     #if INTERRUPTS_IN_NATIVE_MODE
1711     case MODE_NATIVE:
1712     // 68k emulator inactive, in nanokernel?
1713 gbeauche 1.26 if (r->gpr(1) != KernelDataAddr) {
1714 gbeauche 1.33
1715     // Set extra stack for nested interrupts
1716     sig_stack_acquire();
1717    
1718 cebix 1.1 // Prepare for 68k interrupt level 1
1719     WriteMacInt16(ntohl(kernel_data->v[0x67c >> 2]), 1);
1720     WriteMacInt32(ntohl(kernel_data->v[0x658 >> 2]) + 0xdc, ReadMacInt32(ntohl(kernel_data->v[0x658 >> 2]) + 0xdc) | ntohl(kernel_data->v[0x674 >> 2]));
1721    
1722     // Execute nanokernel interrupt routine (this will activate the 68k emulator)
1723 gbeauche 1.33 DisableInterrupt();
1724 cebix 1.1 if (ROMType == ROMTYPE_NEWWORLD)
1725     ppc_interrupt(ROM_BASE + 0x312b1c, KernelDataAddr);
1726     else
1727     ppc_interrupt(ROM_BASE + 0x312a3c, KernelDataAddr);
1728 gbeauche 1.33
1729     // Reset normal signal stack
1730     sig_stack_release();
1731 cebix 1.1 }
1732     break;
1733     #endif
1734    
1735     #if INTERRUPTS_IN_EMUL_OP_MODE
1736     case MODE_EMUL_OP:
1737     // 68k emulator active, within EMUL_OP routine, execute 68k interrupt routine directly when interrupt level is 0
1738     if ((ReadMacInt32(XLM_68K_R25) & 7) == 0) {
1739    
1740     // Set extra stack for SIGSEGV handler
1741 gbeauche 1.33 sig_stack_acquire();
1742 cebix 1.1 #if 1
1743     // Execute full 68k interrupt routine
1744     M68kRegisters r;
1745     uint32 old_r25 = ReadMacInt32(XLM_68K_R25); // Save interrupt level
1746     WriteMacInt32(XLM_68K_R25, 0x21); // Execute with interrupt level 1
1747     static const uint16 proc[] = {
1748     0x3f3c, 0x0000, // move.w #$0000,-(sp) (fake format word)
1749     0x487a, 0x000a, // pea @1(pc) (return address)
1750     0x40e7, // move sr,-(sp) (saved SR)
1751     0x2078, 0x0064, // move.l $64,a0
1752     0x4ed0, // jmp (a0)
1753     M68K_RTS // @1
1754     };
1755     Execute68k((uint32)proc, &r);
1756     WriteMacInt32(XLM_68K_R25, old_r25); // Restore interrupt level
1757     #else
1758     // Only update cursor
1759     if (HasMacStarted()) {
1760     if (InterruptFlags & INTFLAG_VIA) {
1761     ClearInterruptFlag(INTFLAG_VIA);
1762     ADBInterrupt();
1763 gbeauche 1.17 ExecuteNative(NATIVE_VIDEO_VBL);
1764 cebix 1.1 }
1765     }
1766     #endif
1767     // Reset normal signal stack
1768 gbeauche 1.33 sig_stack_release();
1769 cebix 1.1 }
1770     break;
1771     #endif
1772     }
1773     }
1774 gbeauche 1.8 #endif
1775 cebix 1.1
1776    
1777     /*
1778     * SIGSEGV handler
1779     */
1780    
1781 gbeauche 1.8 #if !EMULATED_PPC
1782 gbeauche 1.26 static void sigsegv_handler(int sig, siginfo_t *sip, void *scp)
1783 cebix 1.1 {
1784 gbeauche 1.26 machine_regs *r = MACHINE_REGISTERS(scp);
1785 gbeauche 1.5
1786     // Get effective address
1787 gbeauche 1.26 uint32 addr = r->dar();
1788 gbeauche 1.5
1789     #if ENABLE_VOSF
1790     // Handle screen fault.
1791     extern bool Screen_fault_handler(sigsegv_address_t fault_address, sigsegv_address_t fault_instruction);
1792 gbeauche 1.26 if (Screen_fault_handler((sigsegv_address_t)addr, (sigsegv_address_t)r->pc()))
1793 gbeauche 1.5 return;
1794     #endif
1795    
1796 cebix 1.1 num_segv++;
1797    
1798 gbeauche 1.37 // Fault in Mac ROM or RAM or DR Cache?
1799     bool mac_fault = (r->pc() >= ROM_BASE) && (r->pc() < (ROM_BASE + ROM_AREA_SIZE)) || (r->pc() >= RAMBase) && (r->pc() < (RAMBase + RAMSize)) || (r->pc() >= DR_CACHE_BASE && r->pc() < (DR_CACHE_BASE + DR_CACHE_SIZE));
1800 cebix 1.1 if (mac_fault) {
1801    
1802     // "VM settings" during MacOS 8 installation
1803 gbeauche 1.26 if (r->pc() == ROM_BASE + 0x488160 && r->gpr(20) == 0xf8000000) {
1804     r->pc() += 4;
1805     r->gpr(8) = 0;
1806 cebix 1.1 return;
1807    
1808     // MacOS 8.5 installation
1809 gbeauche 1.26 } else if (r->pc() == ROM_BASE + 0x488140 && r->gpr(16) == 0xf8000000) {
1810     r->pc() += 4;
1811     r->gpr(8) = 0;
1812 cebix 1.1 return;
1813    
1814     // MacOS 8 serial drivers on startup
1815 gbeauche 1.26 } else if (r->pc() == ROM_BASE + 0x48e080 && (r->gpr(8) == 0xf3012002 || r->gpr(8) == 0xf3012000)) {
1816     r->pc() += 4;
1817     r->gpr(8) = 0;
1818 cebix 1.1 return;
1819    
1820     // MacOS 8.1 serial drivers on startup
1821 gbeauche 1.26 } else if (r->pc() == ROM_BASE + 0x48c5e0 && (r->gpr(20) == 0xf3012002 || r->gpr(20) == 0xf3012000)) {
1822     r->pc() += 4;
1823 cebix 1.1 return;
1824 gbeauche 1.26 } else if (r->pc() == ROM_BASE + 0x4a10a0 && (r->gpr(20) == 0xf3012002 || r->gpr(20) == 0xf3012000)) {
1825     r->pc() += 4;
1826 cebix 1.1 return;
1827 gbeauche 1.37
1828     // MacOS 8.6 serial drivers on startup (with DR Cache and OldWorld ROM)
1829     } else if ((r->pc() - DR_CACHE_BASE) < DR_CACHE_SIZE && (r->gpr(16) == 0xf3012002 || r->gpr(16) == 0xf3012000)) {
1830     r->pc() += 4;
1831     return;
1832     } else if ((r->pc() - DR_CACHE_BASE) < DR_CACHE_SIZE && (r->gpr(20) == 0xf3012002 || r->gpr(20) == 0xf3012000)) {
1833     r->pc() += 4;
1834     return;
1835 cebix 1.1 }
1836    
1837 gbeauche 1.5 // Get opcode and divide into fields
1838 gbeauche 1.26 uint32 opcode = *((uint32 *)r->pc());
1839 gbeauche 1.5 uint32 primop = opcode >> 26;
1840     uint32 exop = (opcode >> 1) & 0x3ff;
1841     uint32 ra = (opcode >> 16) & 0x1f;
1842     uint32 rb = (opcode >> 11) & 0x1f;
1843     uint32 rd = (opcode >> 21) & 0x1f;
1844     int32 imm = (int16)(opcode & 0xffff);
1845    
1846 cebix 1.1 // Analyze opcode
1847     enum {
1848     TYPE_UNKNOWN,
1849     TYPE_LOAD,
1850     TYPE_STORE
1851     } transfer_type = TYPE_UNKNOWN;
1852     enum {
1853     SIZE_UNKNOWN,
1854     SIZE_BYTE,
1855     SIZE_HALFWORD,
1856     SIZE_WORD
1857     } transfer_size = SIZE_UNKNOWN;
1858     enum {
1859     MODE_UNKNOWN,
1860     MODE_NORM,
1861     MODE_U,
1862     MODE_X,
1863     MODE_UX
1864     } addr_mode = MODE_UNKNOWN;
1865     switch (primop) {
1866     case 31:
1867     switch (exop) {
1868     case 23: // lwzx
1869     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
1870     case 55: // lwzux
1871     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
1872     case 87: // lbzx
1873     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
1874     case 119: // lbzux
1875     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
1876     case 151: // stwx
1877     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
1878     case 183: // stwux
1879     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
1880     case 215: // stbx
1881     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
1882     case 247: // stbux
1883     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
1884     case 279: // lhzx
1885     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1886     case 311: // lhzux
1887     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1888     case 343: // lhax
1889     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1890     case 375: // lhaux
1891     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1892     case 407: // sthx
1893     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1894     case 439: // sthux
1895     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1896     }
1897     break;
1898    
1899     case 32: // lwz
1900     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
1901     case 33: // lwzu
1902     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
1903     case 34: // lbz
1904     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
1905     case 35: // lbzu
1906     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
1907     case 36: // stw
1908     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
1909     case 37: // stwu
1910     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
1911     case 38: // stb
1912     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
1913     case 39: // stbu
1914     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
1915     case 40: // lhz
1916     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1917     case 41: // lhzu
1918     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1919     case 42: // lha
1920     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1921     case 43: // lhau
1922     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1923     case 44: // sth
1924     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1925     case 45: // sthu
1926     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1927 gbeauche 1.23 #if EMULATE_UNALIGNED_LOADSTORE_MULTIPLE
1928     case 46: // lmw
1929 gbeauche 1.27 if ((addr % 4) != 0) {
1930     uint32 ea = addr;
1931 gbeauche 1.26 D(bug("WARNING: unaligned lmw to EA=%08x from IP=%08x\n", ea, r->pc()));
1932 gbeauche 1.23 for (int i = rd; i <= 31; i++) {
1933 gbeauche 1.26 r->gpr(i) = ReadMacInt32(ea);
1934 gbeauche 1.23 ea += 4;
1935     }
1936 gbeauche 1.26 r->pc() += 4;
1937 gbeauche 1.23 goto rti;
1938     }
1939     break;
1940     case 47: // stmw
1941 gbeauche 1.27 if ((addr % 4) != 0) {
1942     uint32 ea = addr;
1943 gbeauche 1.26 D(bug("WARNING: unaligned stmw to EA=%08x from IP=%08x\n", ea, r->pc()));
1944 gbeauche 1.23 for (int i = rd; i <= 31; i++) {
1945 gbeauche 1.26 WriteMacInt32(ea, r->gpr(i));
1946 gbeauche 1.23 ea += 4;
1947     }
1948 gbeauche 1.26 r->pc() += 4;
1949 gbeauche 1.23 goto rti;
1950     }
1951     break;
1952     #endif
1953 cebix 1.1 }
1954    
1955 gbeauche 1.31 // Ignore ROM writes (including to the zero page, which is read-only)
1956     if (transfer_type == TYPE_STORE &&
1957     ((addr >= ROM_BASE && addr < ROM_BASE + ROM_SIZE) ||
1958     (addr >= SheepMem::ZeroPage() && addr < SheepMem::ZeroPage() + SheepMem::PageSize()))) {
1959 gbeauche 1.26 // 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->pc()));
1960 cebix 1.1 if (addr_mode == MODE_U || addr_mode == MODE_UX)
1961 gbeauche 1.26 r->gpr(ra) = addr;
1962     r->pc() += 4;
1963 cebix 1.1 goto rti;
1964     }
1965    
1966     // Ignore illegal memory accesses?
1967     if (PrefsFindBool("ignoresegv")) {
1968     if (addr_mode == MODE_U || addr_mode == MODE_UX)
1969 gbeauche 1.26 r->gpr(ra) = addr;
1970 cebix 1.1 if (transfer_type == TYPE_LOAD)
1971 gbeauche 1.26 r->gpr(rd) = 0;
1972     r->pc() += 4;
1973 cebix 1.1 goto rti;
1974     }
1975    
1976     // In GUI mode, show error alert
1977     if (!PrefsFindBool("nogui")) {
1978     char str[256];
1979     if (transfer_type == TYPE_LOAD || transfer_type == TYPE_STORE)
1980 gbeauche 1.26 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->pc(), r->gpr(24), r->gpr(1));
1981 cebix 1.1 else
1982 gbeauche 1.26 sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->pc(), r->gpr(24), r->gpr(1), opcode);
1983 cebix 1.1 ErrorAlert(str);
1984     QuitEmulator();
1985     return;
1986     }
1987     }
1988    
1989     // For all other errors, jump into debugger (sort of...)
1990 gbeauche 1.23 crash_reason = (sig == SIGBUS) ? "SIGBUS" : "SIGSEGV";
1991 cebix 1.1 if (!ready_for_signals) {
1992 gbeauche 1.23 printf("%s\n");
1993 gbeauche 1.26 printf(" sigcontext %p, machine_regs %p\n", scp, r);
1994 cebix 1.1 printf(
1995     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1996     " xer %08lx cr %08lx \n"
1997     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1998     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1999     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
2000     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
2001     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
2002     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
2003     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
2004     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
2005 gbeauche 1.23 crash_reason,
2006 gbeauche 1.26 r->pc(), r->lr(), r->ctr(), r->msr(),
2007     r->xer(), r->cr(),
2008     r->gpr(0), r->gpr(1), r->gpr(2), r->gpr(3),
2009     r->gpr(4), r->gpr(5), r->gpr(6), r->gpr(7),
2010     r->gpr(8), r->gpr(9), r->gpr(10), r->gpr(11),
2011     r->gpr(12), r->gpr(13), r->gpr(14), r->gpr(15),
2012     r->gpr(16), r->gpr(17), r->gpr(18), r->gpr(19),
2013     r->gpr(20), r->gpr(21), r->gpr(22), r->gpr(23),
2014     r->gpr(24), r->gpr(25), r->gpr(26), r->gpr(27),
2015     r->gpr(28), r->gpr(29), r->gpr(30), r->gpr(31));
2016 cebix 1.1 exit(1);
2017     QuitEmulator();
2018     return;
2019     } else {
2020     // We crashed. Save registers, tell tick thread and loop forever
2021 gbeauche 1.26 build_sigregs(&sigsegv_regs, r);
2022 cebix 1.1 emul_thread_fatal = true;
2023     for (;;) ;
2024     }
2025     rti:;
2026     }
2027    
2028    
2029     /*
2030     * SIGILL handler
2031     */
2032    
2033 gbeauche 1.26 static void sigill_handler(int sig, siginfo_t *sip, void *scp)
2034 cebix 1.1 {
2035 gbeauche 1.26 machine_regs *r = MACHINE_REGISTERS(scp);
2036 cebix 1.1 char str[256];
2037    
2038     // Fault in Mac ROM or RAM?
2039 gbeauche 1.26 bool mac_fault = (r->pc() >= ROM_BASE) && (r->pc() < (ROM_BASE + ROM_AREA_SIZE)) || (r->pc() >= RAMBase) && (r->pc() < (RAMBase + RAMSize));
2040 cebix 1.1 if (mac_fault) {
2041    
2042     // Get opcode and divide into fields
2043 gbeauche 1.26 uint32 opcode = *((uint32 *)r->pc());
2044 cebix 1.1 uint32 primop = opcode >> 26;
2045     uint32 exop = (opcode >> 1) & 0x3ff;
2046     uint32 ra = (opcode >> 16) & 0x1f;
2047     uint32 rb = (opcode >> 11) & 0x1f;
2048     uint32 rd = (opcode >> 21) & 0x1f;
2049     int32 imm = (int16)(opcode & 0xffff);
2050    
2051     switch (primop) {
2052     case 9: // POWER instructions
2053     case 22:
2054 gbeauche 1.26 power_inst: sprintf(str, GetString(STR_POWER_INSTRUCTION_ERR), r->pc(), r->gpr(1), opcode);
2055 cebix 1.1 ErrorAlert(str);
2056     QuitEmulator();
2057     return;
2058    
2059     case 31:
2060     switch (exop) {
2061     case 83: // mfmsr
2062 gbeauche 1.26 r->gpr(rd) = 0xf072;
2063     r->pc() += 4;
2064 cebix 1.1 goto rti;
2065    
2066     case 210: // mtsr
2067     case 242: // mtsrin
2068     case 306: // tlbie
2069 gbeauche 1.26 r->pc() += 4;
2070 cebix 1.1 goto rti;
2071    
2072     case 339: { // mfspr
2073     int spr = ra | (rb << 5);
2074     switch (spr) {
2075     case 0: // MQ
2076     case 22: // DEC
2077     case 952: // MMCR0
2078     case 953: // PMC1
2079     case 954: // PMC2
2080     case 955: // SIA
2081     case 956: // MMCR1
2082     case 957: // PMC3
2083     case 958: // PMC4
2084     case 959: // SDA
2085 gbeauche 1.26 r->pc() += 4;
2086 cebix 1.1 goto rti;
2087     case 25: // SDR1
2088 gbeauche 1.26 r->gpr(rd) = 0xdead001f;
2089     r->pc() += 4;
2090 cebix 1.1 goto rti;
2091     case 287: // PVR
2092 gbeauche 1.26 r->gpr(rd) = PVR;
2093     r->pc() += 4;
2094 cebix 1.1 goto rti;
2095     }
2096     break;
2097     }
2098    
2099     case 467: { // mtspr
2100     int spr = ra | (rb << 5);
2101     switch (spr) {
2102     case 0: // MQ
2103     case 22: // DEC
2104     case 275: // SPRG3
2105     case 528: // IBAT0U
2106     case 529: // IBAT0L
2107     case 530: // IBAT1U
2108     case 531: // IBAT1L
2109     case 532: // IBAT2U
2110     case 533: // IBAT2L
2111     case 534: // IBAT3U
2112     case 535: // IBAT3L
2113     case 536: // DBAT0U
2114     case 537: // DBAT0L
2115     case 538: // DBAT1U
2116     case 539: // DBAT1L
2117     case 540: // DBAT2U
2118     case 541: // DBAT2L
2119     case 542: // DBAT3U
2120     case 543: // DBAT3L
2121     case 952: // MMCR0
2122     case 953: // PMC1
2123     case 954: // PMC2
2124     case 955: // SIA
2125     case 956: // MMCR1
2126     case 957: // PMC3
2127     case 958: // PMC4
2128     case 959: // SDA
2129 gbeauche 1.26 r->pc() += 4;
2130 cebix 1.1 goto rti;
2131     }
2132     break;
2133     }
2134    
2135     case 29: case 107: case 152: case 153: // POWER instructions
2136     case 184: case 216: case 217: case 248:
2137     case 264: case 277: case 331: case 360:
2138     case 363: case 488: case 531: case 537:
2139     case 541: case 664: case 665: case 696:
2140     case 728: case 729: case 760: case 920:
2141     case 921: case 952:
2142     goto power_inst;
2143     }
2144     }
2145    
2146     // In GUI mode, show error alert
2147     if (!PrefsFindBool("nogui")) {
2148 gbeauche 1.26 sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->pc(), r->gpr(24), r->gpr(1), opcode);
2149 cebix 1.1 ErrorAlert(str);
2150     QuitEmulator();
2151     return;
2152     }
2153     }
2154    
2155     // For all other errors, jump into debugger (sort of...)
2156 gbeauche 1.23 crash_reason = "SIGILL";
2157 cebix 1.1 if (!ready_for_signals) {
2158 gbeauche 1.23 printf("%s\n");
2159 gbeauche 1.26 printf(" sigcontext %p, machine_regs %p\n", scp, r);
2160 cebix 1.1 printf(
2161     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
2162     " xer %08lx cr %08lx \n"
2163     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
2164     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
2165     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
2166     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
2167     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
2168     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
2169     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
2170     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
2171 gbeauche 1.23 crash_reason,
2172 gbeauche 1.26 r->pc(), r->lr(), r->ctr(), r->msr(),
2173     r->xer(), r->cr(),
2174     r->gpr(0), r->gpr(1), r->gpr(2), r->gpr(3),
2175     r->gpr(4), r->gpr(5), r->gpr(6), r->gpr(7),
2176     r->gpr(8), r->gpr(9), r->gpr(10), r->gpr(11),
2177     r->gpr(12), r->gpr(13), r->gpr(14), r->gpr(15),
2178     r->gpr(16), r->gpr(17), r->gpr(18), r->gpr(19),
2179     r->gpr(20), r->gpr(21), r->gpr(22), r->gpr(23),
2180     r->gpr(24), r->gpr(25), r->gpr(26), r->gpr(27),
2181     r->gpr(28), r->gpr(29), r->gpr(30), r->gpr(31));
2182 cebix 1.1 exit(1);
2183     QuitEmulator();
2184     return;
2185     } else {
2186     // We crashed. Save registers, tell tick thread and loop forever
2187 gbeauche 1.26 build_sigregs(&sigsegv_regs, r);
2188 cebix 1.1 emul_thread_fatal = true;
2189     for (;;) ;
2190     }
2191     rti:;
2192     }
2193     #endif
2194 gbeauche 1.15
2195    
2196     /*
2197     * Helpers to share 32-bit addressable data with MacOS
2198     */
2199    
2200     bool SheepMem::Init(void)
2201     {
2202 gbeauche 1.31 // Size of a native page
2203     page_size = getpagesize();
2204 gbeauche 1.20
2205     // Allocate SheepShaver globals
2206 gbeauche 1.15 if (vm_acquire_fixed((char *)base, size) < 0)
2207     return false;
2208 gbeauche 1.18
2209 gbeauche 1.20 // Allocate page with all bits set to 0
2210 gbeauche 1.18 zero_page = base + size;
2211     if (vm_acquire_fixed((char *)zero_page, page_size) < 0)
2212     return false;
2213 gbeauche 1.19 memset((char *)zero_page, 0, page_size);
2214 gbeauche 1.18 if (vm_protect((char *)zero_page, page_size, VM_PAGE_READ) < 0)
2215     return false;
2216    
2217 gbeauche 1.20 #if EMULATED_PPC
2218     // Allocate alternate stack for PowerPC interrupt routine
2219     sig_stack = zero_page + page_size;
2220     if (vm_acquire_fixed((char *)sig_stack, SIG_STACK_SIZE) < 0)
2221     return false;
2222     #endif
2223    
2224 gbeauche 1.15 top = base + size;
2225     return true;
2226     }
2227    
2228     void SheepMem::Exit(void)
2229     {
2230 gbeauche 1.18 if (top) {
2231 gbeauche 1.20 // Delete SheepShaver globals
2232     vm_release((void *)base, size);
2233    
2234     // Delete zero page
2235     vm_release((void *)zero_page, page_size);
2236    
2237     #if EMULATED_PPC
2238     // Delete alternate stack for PowerPC interrupt routine
2239     vm_release((void *)sig_stack, SIG_STACK_SIZE);
2240     #endif
2241 gbeauche 1.18 }
2242 gbeauche 1.15 }
2243 cebix 1.1
2244    
2245     /*
2246     * Display alert
2247     */
2248    
2249     #ifdef ENABLE_GTK
2250     static void dl_destroyed(void)
2251     {
2252     gtk_main_quit();
2253     }
2254    
2255     static void dl_quit(GtkWidget *dialog)
2256     {
2257     gtk_widget_destroy(dialog);
2258     }
2259    
2260     void display_alert(int title_id, int prefix_id, int button_id, const char *text)
2261     {
2262     char str[256];
2263     sprintf(str, GetString(prefix_id), text);
2264    
2265     GtkWidget *dialog = gtk_dialog_new();
2266     gtk_window_set_title(GTK_WINDOW(dialog), GetString(title_id));
2267     gtk_container_border_width(GTK_CONTAINER(dialog), 5);
2268     gtk_widget_set_uposition(GTK_WIDGET(dialog), 100, 150);
2269     gtk_signal_connect(GTK_OBJECT(dialog), "destroy", GTK_SIGNAL_FUNC(dl_destroyed), NULL);
2270    
2271     GtkWidget *label = gtk_label_new(str);
2272     gtk_widget_show(label);
2273     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, TRUE, TRUE, 0);
2274    
2275     GtkWidget *button = gtk_button_new_with_label(GetString(button_id));
2276     gtk_widget_show(button);
2277     gtk_signal_connect_object(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(dl_quit), GTK_OBJECT(dialog));
2278     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area), button, FALSE, FALSE, 0);
2279     GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
2280     gtk_widget_grab_default(button);
2281     gtk_widget_show(dialog);
2282    
2283     gtk_main();
2284     }
2285     #endif
2286    
2287    
2288     /*
2289     * Display error alert
2290     */
2291    
2292     void ErrorAlert(const char *text)
2293     {
2294 gbeauche 1.42 #if defined(ENABLE_GTK) && !defined(USE_SDL_VIDEO)
2295 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
2296     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
2297     return;
2298     }
2299     VideoQuitFullScreen();
2300     display_alert(STR_ERROR_ALERT_TITLE, STR_GUI_ERROR_PREFIX, STR_QUIT_BUTTON, text);
2301     #else
2302     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
2303     #endif
2304     }
2305    
2306    
2307     /*
2308     * Display warning alert
2309     */
2310    
2311     void WarningAlert(const char *text)
2312     {
2313 gbeauche 1.42 #if defined(ENABLE_GTK) && !defined(USE_SDL_VIDEO)
2314 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
2315     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
2316     return;
2317     }
2318     display_alert(STR_WARNING_ALERT_TITLE, STR_GUI_WARNING_PREFIX, STR_OK_BUTTON, text);
2319     #else
2320     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
2321     #endif
2322     }
2323    
2324    
2325     /*
2326     * Display choice alert
2327     */
2328    
2329     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
2330     {
2331     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
2332     return false; //!!
2333     }