ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.38
Committed: 2004-05-31T10:55:42Z (20 years, 5 months ago) by gbeauche
Branch: MAIN
Changes since 1.37: +7 -0 lines
Log Message:
Make DR Cache executable by default in native PowerPC mode.

File Contents

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