ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.28
Committed: 2004-01-18T22:59:06Z (20 years, 9 months ago) by gbeauche
Branch: MAIN
Changes since 1.27: +9 -9 lines
Log Message:
Post-merge fixups: machine state wrappers, Apple assembler perticularities.

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