ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.35
Committed: 2004-05-20T12:33:57Z (20 years, 5 months ago) by gbeauche
Branch: MAIN
Changes since 1.34: +2 -11 lines
Log Message:
Get rid of old (and broken) ASYNC_IRQ / MUTICORE code

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