ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.50
Committed: 2004-07-10T06:15:42Z (20 years, 4 months ago) by gbeauche
Branch: MAIN
Changes since 1.49: +61 -35 lines
Log Message:
Better PowerPC / POWER CPU detection from Linux cpu_specs[] table.

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