ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.29
Committed: 2004-01-31T11:10:49Z (20 years, 9 months ago) by gbeauche
Branch: MAIN
Changes since 1.28: +5 -1 lines
Log Message:
Recognize 7400 & 7410 cpus

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