ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.52
Committed: 2004-11-13T14:09:15Z (20 years ago) by gbeauche
Branch: MAIN
Changes since 1.51: +57 -48 lines
Log Message:
Implement Direct Addressing mode similarly to Basilisk II. This is to get
SheepShaver working on OSes that don't support maipping of Low Memory globals
at 0x00000000, e.g. Windows.

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