ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.33
Committed: 2004-04-14T20:25:26Z (20 years, 7 months ago) by gbeauche
Branch: MAIN
Changes since 1.32: +65 -28 lines
Log Message:
Fix nested ppc_interrupt() stack corruption problem by allocating yet
another stack when next signal is triggered. I am still unsure if
even MacOS would normally handle nested calls to NanoKernel interrupt
routine.

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     static void sigusr2_handler(int sig);
323 gbeauche 1.13 extern void emul_ppc(uint32 start);
324     extern void init_emul_ppc(void);
325     extern void exit_emul_ppc(void);
326 gbeauche 1.8 #else
327 gbeauche 1.26 static void sigusr2_handler(int sig, siginfo_t *sip, void *scp);
328     static void sigsegv_handler(int sig, siginfo_t *sip, void *scp);
329     static void sigill_handler(int sig, siginfo_t *sip, void *scp);
330 cebix 1.1 #endif
331    
332    
333     // From asm_linux.S
334 gbeauche 1.12 #if !EMULATED_PPC
335 cebix 1.1 extern "C" void *get_toc(void);
336     extern "C" void *get_sp(void);
337     extern "C" void flush_icache_range(void *start, void *end);
338     extern "C" void jump_to_rom(uint32 entry, uint32 context);
339     extern "C" void quit_emulator(void);
340     extern "C" void execute_68k(uint32 pc, M68kRegisters *r);
341     extern "C" void ppc_interrupt(uint32 entry, uint32 kernel_data);
342     extern "C" int atomic_add(int *var, int v);
343     extern "C" int atomic_and(int *var, int v);
344     extern "C" int atomic_or(int *var, int v);
345     extern void paranoia_check(void);
346 gbeauche 1.12 #endif
347    
348    
349     #if EMULATED_PPC
350     /*
351 gbeauche 1.20 * Return signal stack base
352     */
353    
354     uintptr SignalStackBase(void)
355     {
356     return sig_stack + SIG_STACK_SIZE;
357     }
358    
359    
360     /*
361 gbeauche 1.12 * Atomic operations
362     */
363    
364     #if HAVE_SPINLOCKS
365     static spinlock_t atomic_ops_lock = SPIN_LOCK_UNLOCKED;
366     #else
367     #define spin_lock(LOCK)
368     #define spin_unlock(LOCK)
369     #endif
370    
371     int atomic_add(int *var, int v)
372     {
373     spin_lock(&atomic_ops_lock);
374     int ret = *var;
375     *var += v;
376     spin_unlock(&atomic_ops_lock);
377     return ret;
378     }
379    
380     int atomic_and(int *var, int v)
381     {
382     spin_lock(&atomic_ops_lock);
383     int ret = *var;
384     *var &= v;
385     spin_unlock(&atomic_ops_lock);
386     return ret;
387     }
388    
389     int atomic_or(int *var, int v)
390     {
391     spin_lock(&atomic_ops_lock);
392     int ret = *var;
393     *var |= v;
394     spin_unlock(&atomic_ops_lock);
395     return ret;
396     }
397 cebix 1.1 #endif
398    
399    
400     /*
401     * Main program
402     */
403    
404     static void usage(const char *prg_name)
405     {
406     printf("Usage: %s [OPTION...]\n", prg_name);
407     printf("\nUnix options:\n");
408     printf(" --display STRING\n X display to use\n");
409     PrefsPrintUsage();
410     exit(0);
411     }
412    
413     int main(int argc, char **argv)
414     {
415     char str[256];
416     uint32 *boot_globs;
417     int16 i16;
418     int rom_fd;
419     FILE *proc_file;
420     const char *rom_path;
421     uint32 rom_size, actual;
422     uint8 *rom_tmp;
423     time_t now, expire;
424    
425     // Initialize variables
426     RAMBase = 0;
427     tzset();
428    
429     // Print some info
430     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
431     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
432    
433     #if !EMULATED_PPC
434     // Get TOC pointer
435     TOC = get_toc();
436     #endif
437    
438     #ifdef ENABLE_GTK
439     // Init GTK
440     gtk_set_locale();
441     gtk_init(&argc, &argv);
442     #endif
443    
444     // Read preferences
445     PrefsInit(argc, argv);
446    
447     // Parse command line arguments
448     for (int i=1; i<argc; i++) {
449     if (strcmp(argv[i], "--help") == 0) {
450     usage(argv[0]);
451     } else if (strcmp(argv[i], "--display") == 0) {
452     i++;
453     if (i < argc)
454     x_display_name = strdup(argv[i]);
455     } else if (argv[i][0] == '-') {
456     fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
457     usage(argv[0]);
458     }
459     }
460    
461     // Open display
462     x_display = XOpenDisplay(x_display_name);
463     if (x_display == NULL) {
464     char str[256];
465     sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
466     ErrorAlert(str);
467     goto quit;
468     }
469    
470     #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
471     // Fork out, so we can return from fullscreen mode when things get ugly
472     XF86DGAForkApp(DefaultScreen(x_display));
473     #endif
474    
475     #ifdef ENABLE_MON
476     // Initialize mon
477     mon_init();
478     #endif
479    
480     // Get system info
481     PVR = 0x00040000; // Default: 604
482     CPUClockSpeed = 100000000; // Default: 100MHz
483     BusClockSpeed = 100000000; // Default: 100MHz
484 gbeauche 1.30 #if EMULATED_PPC
485     PVR = 0x000c0000; // Default: 7400 (with AltiVec)
486     #else
487 cebix 1.1 proc_file = fopen("/proc/cpuinfo", "r");
488     if (proc_file) {
489     char line[256];
490     while(fgets(line, 255, proc_file)) {
491     // Read line
492     int len = strlen(line);
493     if (len == 0)
494     continue;
495     line[len-1] = 0;
496    
497     // Parse line
498     int i;
499     char value[256];
500 gbeauche 1.29 if (sscanf(line, "cpu : %[0-9A-Za-a]", value) == 1) {
501 cebix 1.1 if (strcmp(value, "601") == 0)
502     PVR = 0x00010000;
503     else if (strcmp(value, "603") == 0)
504     PVR = 0x00030000;
505     else if (strcmp(value, "604") == 0)
506     PVR = 0x00040000;
507     else if (strcmp(value, "603e") == 0)
508     PVR = 0x00060000;
509     else if (strcmp(value, "603ev") == 0)
510     PVR = 0x00070000;
511     else if (strcmp(value, "604e") == 0)
512     PVR = 0x00090000;
513     else if (strcmp(value, "604ev5") == 0)
514     PVR = 0x000a0000;
515     else if (strcmp(value, "750") == 0)
516     PVR = 0x00080000;
517     else if (strcmp(value, "821") == 0)
518     PVR = 0x00320000;
519     else if (strcmp(value, "860") == 0)
520     PVR = 0x00500000;
521 gbeauche 1.29 else if (strcmp(value, "7400") == 0)
522 gbeauche 1.30 PVR = 0x000c0000;
523 gbeauche 1.29 else if (strcmp(value, "7410") == 0)
524     PVR = 0x800c0000;
525 cebix 1.1 else
526     printf("WARNING: Unknown CPU type '%s', assuming 604\n", value);
527     }
528     if (sscanf(line, "clock : %dMHz", &i) == 1)
529     CPUClockSpeed = BusClockSpeed = i * 1000000;
530     }
531     fclose(proc_file);
532     } else {
533     sprintf(str, GetString(STR_PROC_CPUINFO_WARN), strerror(errno));
534     WarningAlert(str);
535     }
536     #endif
537     D(bug("PVR: %08x (assumed)\n", PVR));
538    
539     // Init system routines
540     SysInit();
541    
542     // Show preferences editor
543     if (!PrefsFindBool("nogui"))
544     if (!PrefsEditor())
545     goto quit;
546    
547     #if !EMULATED_PPC
548     // Check some things
549     paranoia_check();
550     #endif
551    
552     // Open /dev/zero
553     zero_fd = open("/dev/zero", O_RDWR);
554     if (zero_fd < 0) {
555     sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
556     ErrorAlert(str);
557     goto quit;
558     }
559    
560 gbeauche 1.26 #ifndef PAGEZERO_HACK
561 cebix 1.1 // Create Low Memory area (0x0000..0x3000)
562 gbeauche 1.4 if (vm_acquire_fixed((char *)0, 0x3000) < 0) {
563 cebix 1.1 sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
564     ErrorAlert(str);
565     goto quit;
566     }
567     lm_area_mapped = true;
568 gbeauche 1.26 #endif
569 cebix 1.1
570     // Create areas for Kernel Data
571     kernel_area = shmget(IPC_PRIVATE, KERNEL_AREA_SIZE, 0600);
572     if (kernel_area == -1) {
573     sprintf(str, GetString(STR_KD_SHMGET_ERR), strerror(errno));
574     ErrorAlert(str);
575     goto quit;
576     }
577     if (shmat(kernel_area, (void *)KERNEL_DATA_BASE, 0) < 0) {
578     sprintf(str, GetString(STR_KD_SHMAT_ERR), strerror(errno));
579     ErrorAlert(str);
580     goto quit;
581     }
582     if (shmat(kernel_area, (void *)KERNEL_DATA2_BASE, 0) < 0) {
583     sprintf(str, GetString(STR_KD2_SHMAT_ERR), strerror(errno));
584     ErrorAlert(str);
585     goto quit;
586     }
587 gbeauche 1.15 kernel_data = (KernelData *)KERNEL_DATA_BASE;
588 cebix 1.1 emulator_data = &kernel_data->ed;
589 gbeauche 1.15 KernelDataAddr = KERNEL_DATA_BASE;
590 cebix 1.1 D(bug("Kernel Data at %p, Emulator Data at %p\n", kernel_data, emulator_data));
591    
592 gbeauche 1.8 // Create area for SheepShaver data
593 gbeauche 1.15 if (!SheepMem::Init()) {
594 gbeauche 1.8 sprintf(str, GetString(STR_SHEEP_MEM_MMAP_ERR), strerror(errno));
595     ErrorAlert(str);
596     goto quit;
597     }
598    
599 cebix 1.1 // Create area for Mac ROM
600 gbeauche 1.4 if (vm_acquire_fixed((char *)ROM_BASE, ROM_AREA_SIZE) < 0) {
601 cebix 1.1 sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
602     ErrorAlert(str);
603     goto quit;
604     }
605 gbeauche 1.27 #if !EMULATED_PPC
606 gbeauche 1.4 if (vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
607     sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
608     ErrorAlert(str);
609     goto quit;
610     }
611     #endif
612 cebix 1.1 rom_area_mapped = true;
613     D(bug("ROM area at %08x\n", ROM_BASE));
614    
615     // Create area for Mac RAM
616     RAMSize = PrefsFindInt32("ramsize");
617     if (RAMSize < 8*1024*1024) {
618     WarningAlert(GetString(STR_SMALL_RAM_WARN));
619     RAMSize = 8*1024*1024;
620     }
621    
622 gbeauche 1.8 if (vm_acquire_fixed((char *)RAM_BASE, RAMSize) < 0) {
623 cebix 1.1 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
624     ErrorAlert(str);
625     goto quit;
626     }
627 gbeauche 1.4 #if !EMULATED_PPC
628 gbeauche 1.8 if (vm_protect((char *)RAM_BASE, RAMSize, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
629 gbeauche 1.4 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
630     ErrorAlert(str);
631     goto quit;
632     }
633     #endif
634 gbeauche 1.8 RAMBase = RAM_BASE;
635 cebix 1.1 ram_area_mapped = true;
636     D(bug("RAM area at %08x\n", RAMBase));
637    
638     if (RAMBase > ROM_BASE) {
639     ErrorAlert(GetString(STR_RAM_HIGHER_THAN_ROM_ERR));
640     goto quit;
641     }
642    
643     // Load Mac ROM
644     rom_path = PrefsFindString("rom");
645     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
646     if (rom_fd < 0) {
647     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME2, O_RDONLY);
648     if (rom_fd < 0) {
649     ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
650     goto quit;
651     }
652     }
653     printf(GetString(STR_READING_ROM_FILE));
654     rom_size = lseek(rom_fd, 0, SEEK_END);
655     lseek(rom_fd, 0, SEEK_SET);
656     rom_tmp = new uint8[ROM_SIZE];
657     actual = read(rom_fd, (void *)rom_tmp, ROM_SIZE);
658     close(rom_fd);
659 gbeauche 1.3
660     // Decode Mac ROM
661     if (!DecodeROM(rom_tmp, actual)) {
662     if (rom_size != 4*1024*1024) {
663 cebix 1.1 ErrorAlert(GetString(STR_ROM_SIZE_ERR));
664     goto quit;
665     } else {
666     ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
667     goto quit;
668     }
669     }
670 gbeauche 1.3 delete[] rom_tmp;
671 cebix 1.1
672     // Load NVRAM
673     XPRAMInit();
674    
675 gbeauche 1.32 // Load XPRAM default values if signature not found
676     if (XPRAM[0x130c] != 0x4e || XPRAM[0x130d] != 0x75
677     || XPRAM[0x130e] != 0x4d || XPRAM[0x130f] != 0x63) {
678     D(bug("Loading XPRAM default values\n"));
679     memset(XPRAM + 0x1300, 0, 0x100);
680     XPRAM[0x130c] = 0x4e; // "NuMc" signature
681     XPRAM[0x130d] = 0x75;
682     XPRAM[0x130e] = 0x4d;
683     XPRAM[0x130f] = 0x63;
684     XPRAM[0x1301] = 0x80; // InternalWaitFlags = DynWait (don't wait for SCSI devices upon bootup)
685     XPRAM[0x1310] = 0xa8; // Standard PRAM values
686     XPRAM[0x1311] = 0x00;
687     XPRAM[0x1312] = 0x00;
688     XPRAM[0x1313] = 0x22;
689     XPRAM[0x1314] = 0xcc;
690     XPRAM[0x1315] = 0x0a;
691     XPRAM[0x1316] = 0xcc;
692     XPRAM[0x1317] = 0x0a;
693     XPRAM[0x131c] = 0x00;
694     XPRAM[0x131d] = 0x02;
695     XPRAM[0x131e] = 0x63;
696     XPRAM[0x131f] = 0x00;
697     XPRAM[0x1308] = 0x13;
698     XPRAM[0x1309] = 0x88;
699     XPRAM[0x130a] = 0x00;
700     XPRAM[0x130b] = 0xcc;
701     XPRAM[0x1376] = 0x00; // OSDefault = MacOS
702     XPRAM[0x1377] = 0x01;
703     }
704    
705 cebix 1.1 // Set boot volume
706 cebix 1.10 i16 = PrefsFindInt32("bootdrive");
707 cebix 1.1 XPRAM[0x1378] = i16 >> 8;
708     XPRAM[0x1379] = i16 & 0xff;
709 cebix 1.10 i16 = PrefsFindInt32("bootdriver");
710 cebix 1.1 XPRAM[0x137a] = i16 >> 8;
711     XPRAM[0x137b] = i16 & 0xff;
712    
713     // Create BootGlobs at top of Mac memory
714     memset((void *)(RAMBase + RAMSize - 4096), 0, 4096);
715     BootGlobsAddr = RAMBase + RAMSize - 0x1c;
716     boot_globs = (uint32 *)BootGlobsAddr;
717     boot_globs[-5] = htonl(RAMBase + RAMSize); // MemTop
718     boot_globs[0] = htonl(RAMBase); // First RAM bank
719     boot_globs[1] = htonl(RAMSize);
720     boot_globs[2] = htonl((uint32)-1); // End of bank table
721    
722 gbeauche 1.15 // Init thunks
723     if (!ThunksInit())
724     goto quit;
725    
726 cebix 1.1 // Init drivers
727     SonyInit();
728     DiskInit();
729     CDROMInit();
730     SCSIInit();
731    
732     // Init external file system
733     ExtFSInit();
734    
735 gbeauche 1.22 // Init ADB
736     ADBInit();
737    
738 cebix 1.1 // Init audio
739     AudioInit();
740    
741     // Init network
742     EtherInit();
743    
744     // Init serial ports
745     SerialInit();
746    
747     // Init Time Manager
748     TimerInit();
749    
750     // Init clipboard
751     ClipInit();
752    
753     // Init video
754     if (!VideoInit())
755     goto quit;
756    
757     // Install ROM patches
758     if (!PatchROM()) {
759     ErrorAlert(GetString(STR_UNSUPPORTED_ROM_TYPE_ERR));
760     goto quit;
761     }
762    
763     // Clear caches (as we loaded and patched code) and write protect ROM
764     #if !EMULATED_PPC
765     MakeExecutable(0, (void *)ROM_BASE, ROM_AREA_SIZE);
766     #endif
767 gbeauche 1.4 vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_EXECUTE);
768 cebix 1.1
769     // Initialize Kernel Data
770     memset(kernel_data, 0, sizeof(KernelData));
771     if (ROMType == ROMTYPE_NEWWORLD) {
772 gbeauche 1.15 uintptr of_dev_tree = SheepMem::Reserve(4 * sizeof(uint32));
773     memset((void *)of_dev_tree, 0, 4 * sizeof(uint32));
774     uintptr vector_lookup_tbl = SheepMem::Reserve(128);
775     uintptr vector_mask_tbl = SheepMem::Reserve(64);
776 cebix 1.1 memset((uint8 *)kernel_data + 0xb80, 0x3d, 0x80);
777 gbeauche 1.15 memset((void *)vector_lookup_tbl, 0, 128);
778     memset((void *)vector_mask_tbl, 0, 64);
779 cebix 1.1 kernel_data->v[0xb80 >> 2] = htonl(ROM_BASE);
780 gbeauche 1.15 kernel_data->v[0xb84 >> 2] = htonl(of_dev_tree); // OF device tree base
781     kernel_data->v[0xb90 >> 2] = htonl(vector_lookup_tbl);
782     kernel_data->v[0xb94 >> 2] = htonl(vector_mask_tbl);
783 cebix 1.1 kernel_data->v[0xb98 >> 2] = htonl(ROM_BASE); // OpenPIC base
784     kernel_data->v[0xbb0 >> 2] = htonl(0); // ADB base
785     kernel_data->v[0xc20 >> 2] = htonl(RAMSize);
786     kernel_data->v[0xc24 >> 2] = htonl(RAMSize);
787     kernel_data->v[0xc30 >> 2] = htonl(RAMSize);
788     kernel_data->v[0xc34 >> 2] = htonl(RAMSize);
789     kernel_data->v[0xc38 >> 2] = htonl(0x00010020);
790     kernel_data->v[0xc3c >> 2] = htonl(0x00200001);
791     kernel_data->v[0xc40 >> 2] = htonl(0x00010000);
792     kernel_data->v[0xc50 >> 2] = htonl(RAMBase);
793     kernel_data->v[0xc54 >> 2] = htonl(RAMSize);
794     kernel_data->v[0xf60 >> 2] = htonl(PVR);
795     kernel_data->v[0xf64 >> 2] = htonl(CPUClockSpeed);
796     kernel_data->v[0xf68 >> 2] = htonl(BusClockSpeed);
797     kernel_data->v[0xf6c >> 2] = htonl(CPUClockSpeed);
798     } else {
799     kernel_data->v[0xc80 >> 2] = htonl(RAMSize);
800     kernel_data->v[0xc84 >> 2] = htonl(RAMSize);
801     kernel_data->v[0xc90 >> 2] = htonl(RAMSize);
802     kernel_data->v[0xc94 >> 2] = htonl(RAMSize);
803     kernel_data->v[0xc98 >> 2] = htonl(0x00010020);
804     kernel_data->v[0xc9c >> 2] = htonl(0x00200001);
805     kernel_data->v[0xca0 >> 2] = htonl(0x00010000);
806     kernel_data->v[0xcb0 >> 2] = htonl(RAMBase);
807     kernel_data->v[0xcb4 >> 2] = htonl(RAMSize);
808     kernel_data->v[0xf80 >> 2] = htonl(PVR);
809     kernel_data->v[0xf84 >> 2] = htonl(CPUClockSpeed);
810     kernel_data->v[0xf88 >> 2] = htonl(BusClockSpeed);
811     kernel_data->v[0xf8c >> 2] = htonl(CPUClockSpeed);
812     }
813    
814     // Initialize extra low memory
815     D(bug("Initializing Low Memory...\n"));
816     memset(NULL, 0, 0x3000);
817     WriteMacInt32(XLM_SIGNATURE, FOURCC('B','a','a','h')); // Signature to detect SheepShaver
818 gbeauche 1.15 WriteMacInt32(XLM_KERNEL_DATA, KernelDataAddr); // For trap replacement routines
819 cebix 1.1 WriteMacInt32(XLM_PVR, PVR); // Theoretical PVR
820     WriteMacInt32(XLM_BUS_CLOCK, BusClockSpeed); // For DriverServicesLib patch
821     WriteMacInt16(XLM_EXEC_RETURN_OPCODE, M68K_EXEC_RETURN); // For Execute68k() (RTS from the executed 68k code will jump here and end 68k mode)
822 gbeauche 1.18 WriteMacInt32(XLM_ZERO_PAGE, SheepMem::ZeroPage()); // Pointer to read-only page with all bits set to 0
823 gbeauche 1.17 #if !EMULATED_PPC
824     WriteMacInt32(XLM_TOC, (uint32)TOC); // TOC pointer of emulator
825     #endif
826     WriteMacInt32(XLM_ETHER_INIT, NativeFunction(NATIVE_ETHER_INIT)); // DLPI ethernet driver functions
827 gbeauche 1.15 WriteMacInt32(XLM_ETHER_TERM, NativeFunction(NATIVE_ETHER_TERM));
828     WriteMacInt32(XLM_ETHER_OPEN, NativeFunction(NATIVE_ETHER_OPEN));
829     WriteMacInt32(XLM_ETHER_CLOSE, NativeFunction(NATIVE_ETHER_CLOSE));
830     WriteMacInt32(XLM_ETHER_WPUT, NativeFunction(NATIVE_ETHER_WPUT));
831     WriteMacInt32(XLM_ETHER_RSRV, NativeFunction(NATIVE_ETHER_RSRV));
832     WriteMacInt32(XLM_VIDEO_DOIO, NativeFunction(NATIVE_VIDEO_DO_DRIVER_IO));
833 cebix 1.1 D(bug("Low Memory initialized\n"));
834    
835     // Start 60Hz thread
836     tick_thread_active = (pthread_create(&tick_thread, NULL, tick_func, NULL) == 0);
837     D(bug("Tick thread installed (%ld)\n", tick_thread));
838    
839     // Start NVRAM watchdog thread
840     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
841     nvram_thread_active = (pthread_create(&nvram_thread, NULL, nvram_func, NULL) == 0);
842     D(bug("NVRAM thread installed (%ld)\n", nvram_thread));
843    
844     #if !EMULATED_PPC
845     // Create and install stacks for signal handlers
846 gbeauche 1.33 for (int i = 0; i < SIG_STACK_COUNT; i++) {
847     void *sig_stack = malloc(SIG_STACK_SIZE);
848     D(bug("Signal stack %d at %p\n", i, sig_stack));
849     if (sig_stack == NULL) {
850     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
851     goto quit;
852     }
853     sig_stacks[i].ss_sp = sig_stack;
854     sig_stacks[i].ss_flags = 0;
855     sig_stacks[i].ss_size = SIG_STACK_SIZE;
856 cebix 1.1 }
857 gbeauche 1.33 sig_stack_id = 0;
858     if (sigaltstack(&sig_stacks[0], NULL) < 0) {
859 cebix 1.1 sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
860     ErrorAlert(str);
861     goto quit;
862     }
863     #endif
864    
865     #if !EMULATED_PPC
866 gbeauche 1.23 // Install SIGSEGV and SIGBUS handlers
867 cebix 1.1 sigemptyset(&sigsegv_action.sa_mask); // Block interrupts during SEGV handling
868     sigaddset(&sigsegv_action.sa_mask, SIGUSR2);
869 gbeauche 1.26 sigsegv_action.sa_sigaction = sigsegv_handler;
870     sigsegv_action.sa_flags = SA_ONSTACK | SA_SIGINFO;
871     #ifdef HAVE_SIGNAL_SA_RESTORER
872 cebix 1.1 sigsegv_action.sa_restorer = NULL;
873 gbeauche 1.26 #endif
874 cebix 1.1 if (sigaction(SIGSEGV, &sigsegv_action, NULL) < 0) {
875     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
876     ErrorAlert(str);
877     goto quit;
878     }
879 gbeauche 1.23 if (sigaction(SIGBUS, &sigsegv_action, NULL) < 0) {
880     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
881     ErrorAlert(str);
882     goto quit;
883     }
884 cebix 1.1
885     // Install SIGILL handler
886     sigemptyset(&sigill_action.sa_mask); // Block interrupts during ILL handling
887     sigaddset(&sigill_action.sa_mask, SIGUSR2);
888 gbeauche 1.26 sigill_action.sa_sigaction = sigill_handler;
889     sigill_action.sa_flags = SA_ONSTACK | SA_SIGINFO;
890     #ifdef HAVE_SIGNAL_SA_RESTORER
891 cebix 1.1 sigill_action.sa_restorer = NULL;
892 gbeauche 1.26 #endif
893 cebix 1.1 if (sigaction(SIGILL, &sigill_action, NULL) < 0) {
894     sprintf(str, GetString(STR_SIGILL_INSTALL_ERR), strerror(errno));
895     ErrorAlert(str);
896     goto quit;
897     }
898 gbeauche 1.6 #endif
899 cebix 1.1
900 gbeauche 1.26 #if !EMULATED_PPC
901 cebix 1.1 // Install interrupt signal handler
902     sigemptyset(&sigusr2_action.sa_mask);
903 gbeauche 1.26 sigusr2_action.sa_sigaction = sigusr2_handler;
904     sigusr2_action.sa_flags = SA_ONSTACK | SA_RESTART | SA_SIGINFO;
905     #ifdef HAVE_SIGNAL_SA_RESTORER
906     sigusr2_action.sa_restorer = NULL;
907 gbeauche 1.8 #endif
908 cebix 1.1 if (sigaction(SIGUSR2, &sigusr2_action, NULL) < 0) {
909     sprintf(str, GetString(STR_SIGUSR2_INSTALL_ERR), strerror(errno));
910     ErrorAlert(str);
911     goto quit;
912     }
913 gbeauche 1.26 #endif
914 cebix 1.1
915     // Get my thread ID and execute MacOS thread function
916     emul_thread = pthread_self();
917     D(bug("MacOS thread is %ld\n", emul_thread));
918     emul_func(NULL);
919    
920     quit:
921     Quit();
922     return 0;
923     }
924    
925    
926     /*
927     * Cleanup and quit
928     */
929    
930     static void Quit(void)
931     {
932 gbeauche 1.13 #if EMULATED_PPC
933     // Exit PowerPC emulation
934     exit_emul_ppc();
935     #endif
936    
937 cebix 1.1 // Stop 60Hz thread
938     if (tick_thread_active) {
939     pthread_cancel(tick_thread);
940     pthread_join(tick_thread, NULL);
941     }
942    
943     // Stop NVRAM watchdog thread
944     if (nvram_thread_active) {
945     pthread_cancel(nvram_thread);
946     pthread_join(nvram_thread, NULL);
947     }
948    
949     #if !EMULATED_PPC
950 gbeauche 1.23 // Uninstall SIGSEGV and SIGBUS handlers
951 cebix 1.1 sigemptyset(&sigsegv_action.sa_mask);
952     sigsegv_action.sa_handler = SIG_DFL;
953     sigsegv_action.sa_flags = 0;
954     sigaction(SIGSEGV, &sigsegv_action, NULL);
955 gbeauche 1.23 sigaction(SIGBUS, &sigsegv_action, NULL);
956 cebix 1.1
957     // Uninstall SIGILL handler
958     sigemptyset(&sigill_action.sa_mask);
959     sigill_action.sa_handler = SIG_DFL;
960     sigill_action.sa_flags = 0;
961     sigaction(SIGILL, &sigill_action, NULL);
962 gbeauche 1.33
963     // Delete stacks for signal handlers
964     for (int i = 0; i < SIG_STACK_COUNT; i++) {
965     void *sig_stack = sig_stacks[i].ss_sp;
966     if (sig_stack)
967     free(sig_stack);
968     }
969 cebix 1.1 #endif
970    
971     // Save NVRAM
972     XPRAMExit();
973    
974     // Exit clipboard
975     ClipExit();
976    
977     // Exit Time Manager
978     TimerExit();
979    
980     // Exit serial
981     SerialExit();
982    
983     // Exit network
984     EtherExit();
985    
986     // Exit audio
987     AudioExit();
988 gbeauche 1.22
989     // Exit ADB
990     ADBExit();
991 cebix 1.1
992     // Exit video
993     VideoExit();
994    
995     // Exit external file system
996     ExtFSExit();
997    
998     // Exit drivers
999     SCSIExit();
1000     CDROMExit();
1001     DiskExit();
1002     SonyExit();
1003    
1004 gbeauche 1.24 // Delete thunks
1005     ThunksExit();
1006    
1007 gbeauche 1.15 // Delete SheepShaver globals
1008     SheepMem::Exit();
1009    
1010 cebix 1.1 // Delete RAM area
1011     if (ram_area_mapped)
1012 gbeauche 1.8 vm_release((char *)RAM_BASE, RAMSize);
1013 cebix 1.1
1014     // Delete ROM area
1015     if (rom_area_mapped)
1016 gbeauche 1.4 vm_release((char *)ROM_BASE, ROM_AREA_SIZE);
1017 cebix 1.1
1018     // Delete Kernel Data area
1019     if (kernel_area >= 0) {
1020     shmdt((void *)KERNEL_DATA_BASE);
1021     shmdt((void *)KERNEL_DATA2_BASE);
1022     shmctl(kernel_area, IPC_RMID, NULL);
1023     }
1024    
1025     // Delete Low Memory area
1026     if (lm_area_mapped)
1027     munmap((char *)0x0000, 0x3000);
1028    
1029     // Close /dev/zero
1030     if (zero_fd > 0)
1031     close(zero_fd);
1032    
1033     // Exit system routines
1034     SysExit();
1035    
1036     // Exit preferences
1037     PrefsExit();
1038    
1039     #ifdef ENABLE_MON
1040     // Exit mon
1041     mon_exit();
1042     #endif
1043    
1044     // Close X11 server connection
1045     if (x_display)
1046     XCloseDisplay(x_display);
1047    
1048     exit(0);
1049     }
1050    
1051    
1052     /*
1053     * Jump into Mac ROM, start 680x0 emulator
1054     */
1055    
1056     #if EMULATED_PPC
1057     void jump_to_rom(uint32 entry)
1058     {
1059     init_emul_ppc();
1060     emul_ppc(entry);
1061     }
1062     #endif
1063    
1064    
1065     /*
1066     * Emulator thread function
1067     */
1068    
1069     static void *emul_func(void *arg)
1070     {
1071     // We're now ready to receive signals
1072     ready_for_signals = true;
1073    
1074     // Decrease priority, so more time-critical things like audio will work better
1075     nice(1);
1076    
1077     // Jump to ROM boot routine
1078     D(bug("Jumping to ROM\n"));
1079     #if EMULATED_PPC
1080     jump_to_rom(ROM_BASE + 0x310000);
1081     #else
1082     jump_to_rom(ROM_BASE + 0x310000, (uint32)emulator_data);
1083     #endif
1084     D(bug("Returned from ROM\n"));
1085    
1086     // We're no longer ready to receive signals
1087     ready_for_signals = false;
1088     return NULL;
1089     }
1090    
1091    
1092     #if !EMULATED_PPC
1093     /*
1094     * Execute 68k subroutine (must be ended with RTS)
1095     * This must only be called by the emul_thread when in EMUL_OP mode
1096     * r->a[7] is unused, the routine runs on the caller's stack
1097     */
1098    
1099     void Execute68k(uint32 pc, M68kRegisters *r)
1100     {
1101     #if SAFE_EXEC_68K
1102     if (ReadMacInt32(XLM_RUN_MODE) != MODE_EMUL_OP)
1103     printf("FATAL: Execute68k() not called from EMUL_OP mode\n");
1104     if (!pthread_equal(pthread_self(), emul_thread))
1105     printf("FATAL: Execute68k() not called from emul_thread\n");
1106     #endif
1107     execute_68k(pc, r);
1108     }
1109    
1110    
1111     /*
1112     * Execute 68k A-Trap from EMUL_OP routine
1113     * r->a[7] is unused, the routine runs on the caller's stack
1114     */
1115    
1116     void Execute68kTrap(uint16 trap, M68kRegisters *r)
1117     {
1118     uint16 proc[2] = {trap, M68K_RTS};
1119     Execute68k((uint32)proc, r);
1120     }
1121 gbeauche 1.7 #endif
1122 cebix 1.1
1123    
1124     /*
1125     * Quit emulator (cause return from jump_to_rom)
1126     */
1127    
1128     void QuitEmulator(void)
1129     {
1130     #if EMULATED_PPC
1131     Quit();
1132     #else
1133     quit_emulator();
1134     #endif
1135     }
1136    
1137    
1138     /*
1139     * Pause/resume emulator
1140     */
1141    
1142     void PauseEmulator(void)
1143     {
1144     pthread_kill(emul_thread, SIGSTOP);
1145     }
1146    
1147     void ResumeEmulator(void)
1148     {
1149     pthread_kill(emul_thread, SIGCONT);
1150     }
1151    
1152    
1153     /*
1154     * Dump 68k registers
1155     */
1156    
1157     void Dump68kRegs(M68kRegisters *r)
1158     {
1159     // Display 68k registers
1160     for (int i=0; i<8; i++) {
1161     printf("d%d: %08x", i, r->d[i]);
1162     if (i == 3 || i == 7)
1163     printf("\n");
1164     else
1165     printf(", ");
1166     }
1167     for (int i=0; i<8; i++) {
1168     printf("a%d: %08x", i, r->a[i]);
1169     if (i == 3 || i == 7)
1170     printf("\n");
1171     else
1172     printf(", ");
1173     }
1174     }
1175    
1176    
1177     /*
1178     * Make code executable
1179     */
1180    
1181     void MakeExecutable(int dummy, void *start, uint32 length)
1182     {
1183 gbeauche 1.9 if (((uintptr)start >= ROM_BASE) && ((uintptr)start < (ROM_BASE + ROM_SIZE)))
1184 cebix 1.1 return;
1185 gbeauche 1.9 #if EMULATED_PPC
1186     FlushCodeCache((uintptr)start, (uintptr)start + length);
1187     #else
1188     flush_icache_range(start, (void *)((uintptr)start + length));
1189 cebix 1.1 #endif
1190     }
1191    
1192    
1193     /*
1194     * Patch things after system startup (gets called by disk driver accRun routine)
1195     */
1196    
1197     void PatchAfterStartup(void)
1198     {
1199 gbeauche 1.6 ExecuteNative(NATIVE_VIDEO_INSTALL_ACCEL);
1200 cebix 1.1 InstallExtFS();
1201     }
1202    
1203    
1204     /*
1205     * NVRAM watchdog thread (saves NVRAM every minute)
1206     */
1207    
1208     static void *nvram_func(void *arg)
1209     {
1210     struct timespec req = {60, 0}; // 1 minute
1211    
1212     for (;;) {
1213     pthread_testcancel();
1214     nanosleep(&req, NULL);
1215     pthread_testcancel();
1216     if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
1217     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
1218     SaveXPRAM();
1219     }
1220     }
1221     return NULL;
1222     }
1223    
1224    
1225     /*
1226     * 60Hz thread (really 60.15Hz)
1227     */
1228    
1229     static void *tick_func(void *arg)
1230     {
1231     int tick_counter = 0;
1232     struct timespec req = {0, 16625000};
1233    
1234     for (;;) {
1235    
1236     // Wait
1237     nanosleep(&req, NULL);
1238    
1239     #if !EMULATED_PPC
1240     // Did we crash?
1241     if (emul_thread_fatal) {
1242    
1243     // Yes, dump registers
1244 gbeauche 1.26 sigregs *r = &sigsegv_regs;
1245 cebix 1.1 char str[256];
1246 gbeauche 1.23 if (crash_reason == NULL)
1247     crash_reason = "SIGSEGV";
1248     sprintf(str, "%s\n"
1249 cebix 1.1 " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1250     " xer %08lx cr %08lx \n"
1251     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1252     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1253     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1254     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1255     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1256     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1257     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1258     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1259 gbeauche 1.23 crash_reason,
1260 cebix 1.1 r->nip, r->link, r->ctr, r->msr,
1261     r->xer, r->ccr,
1262     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1263     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1264     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1265     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1266     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1267     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1268     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1269     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1270     printf(str);
1271     VideoQuitFullScreen();
1272    
1273     #ifdef ENABLE_MON
1274     // Start up mon in real-mode
1275     printf("Welcome to the sheep factory.\n");
1276     char *arg[4] = {"mon", "-m", "-r", NULL};
1277     mon(3, arg);
1278     #endif
1279     return NULL;
1280     }
1281     #endif
1282    
1283     // Pseudo Mac 1Hz interrupt, update local time
1284     if (++tick_counter > 60) {
1285     tick_counter = 0;
1286     WriteMacInt32(0x20c, TimerDateTime());
1287     }
1288    
1289     // Trigger 60Hz interrupt
1290     if (ReadMacInt32(XLM_IRQ_NEST) == 0) {
1291     SetInterruptFlag(INTFLAG_VIA);
1292     TriggerInterrupt();
1293     }
1294     }
1295     return NULL;
1296     }
1297    
1298    
1299     /*
1300 cebix 1.2 * Pthread configuration
1301     */
1302    
1303     void Set_pthread_attr(pthread_attr_t *attr, int priority)
1304     {
1305 gbeauche 1.14 #ifdef HAVE_PTHREADS
1306     pthread_attr_init(attr);
1307     #if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
1308     // Some of these only work for superuser
1309     if (geteuid() == 0) {
1310     pthread_attr_setinheritsched(attr, PTHREAD_EXPLICIT_SCHED);
1311     pthread_attr_setschedpolicy(attr, SCHED_FIFO);
1312     struct sched_param fifo_param;
1313     fifo_param.sched_priority = ((sched_get_priority_min(SCHED_FIFO) +
1314     sched_get_priority_max(SCHED_FIFO)) / 2 +
1315     priority);
1316     pthread_attr_setschedparam(attr, &fifo_param);
1317     }
1318     if (pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM) != 0) {
1319     #ifdef PTHREAD_SCOPE_BOUND_NP
1320     // If system scope is not available (eg. we're not running
1321     // with CAP_SCHED_MGT capability on an SGI box), try bound
1322     // scope. It exposes pthread scheduling to the kernel,
1323     // without setting realtime priority.
1324     pthread_attr_setscope(attr, PTHREAD_SCOPE_BOUND_NP);
1325     #endif
1326     }
1327     #endif
1328     #endif
1329 cebix 1.2 }
1330    
1331    
1332     /*
1333 cebix 1.1 * Mutexes
1334     */
1335    
1336 gbeauche 1.7 #ifdef HAVE_PTHREADS
1337    
1338     struct B2_mutex {
1339     B2_mutex() {
1340     pthread_mutexattr_t attr;
1341     pthread_mutexattr_init(&attr);
1342     // Initialize the mutex for priority inheritance --
1343     // required for accurate timing.
1344     #ifdef HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL
1345     pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
1346     #endif
1347     #if defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE) && defined(PTHREAD_MUTEX_NORMAL)
1348     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
1349     #endif
1350     #ifdef HAVE_PTHREAD_MUTEXATTR_SETPSHARED
1351     pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);
1352     #endif
1353     pthread_mutex_init(&m, &attr);
1354     pthread_mutexattr_destroy(&attr);
1355     }
1356     ~B2_mutex() {
1357     pthread_mutex_trylock(&m); // Make sure it's locked before
1358     pthread_mutex_unlock(&m); // unlocking it.
1359     pthread_mutex_destroy(&m);
1360     }
1361     pthread_mutex_t m;
1362     };
1363    
1364     B2_mutex *B2_create_mutex(void)
1365     {
1366     return new B2_mutex;
1367     }
1368    
1369     void B2_lock_mutex(B2_mutex *mutex)
1370     {
1371     pthread_mutex_lock(&mutex->m);
1372     }
1373    
1374     void B2_unlock_mutex(B2_mutex *mutex)
1375     {
1376     pthread_mutex_unlock(&mutex->m);
1377     }
1378    
1379     void B2_delete_mutex(B2_mutex *mutex)
1380     {
1381     delete mutex;
1382     }
1383    
1384     #else
1385    
1386 cebix 1.1 struct B2_mutex {
1387     int dummy;
1388     };
1389    
1390     B2_mutex *B2_create_mutex(void)
1391     {
1392     return new B2_mutex;
1393     }
1394    
1395     void B2_lock_mutex(B2_mutex *mutex)
1396     {
1397     }
1398    
1399     void B2_unlock_mutex(B2_mutex *mutex)
1400     {
1401     }
1402    
1403     void B2_delete_mutex(B2_mutex *mutex)
1404     {
1405     delete mutex;
1406     }
1407    
1408 gbeauche 1.7 #endif
1409    
1410 cebix 1.1
1411     /*
1412     * Trigger signal USR2 from another thread
1413     */
1414    
1415 gbeauche 1.8 #if !EMULATED_PPC || ASYNC_IRQ
1416 cebix 1.1 void TriggerInterrupt(void)
1417     {
1418     if (ready_for_signals)
1419     pthread_kill(emul_thread, SIGUSR2);
1420     }
1421 gbeauche 1.7 #endif
1422 cebix 1.1
1423    
1424     /*
1425     * Interrupt flags (must be handled atomically!)
1426     */
1427    
1428     volatile uint32 InterruptFlags = 0;
1429    
1430     void SetInterruptFlag(uint32 flag)
1431     {
1432     atomic_or((int *)&InterruptFlags, flag);
1433     }
1434    
1435     void ClearInterruptFlag(uint32 flag)
1436     {
1437     atomic_and((int *)&InterruptFlags, ~flag);
1438     }
1439    
1440    
1441     /*
1442     * Disable interrupts
1443     */
1444    
1445     void DisableInterrupt(void)
1446     {
1447 gbeauche 1.7 atomic_add((int *)XLM_IRQ_NEST, 1);
1448 cebix 1.1 }
1449    
1450    
1451     /*
1452     * Enable interrupts
1453     */
1454    
1455     void EnableInterrupt(void)
1456     {
1457 gbeauche 1.7 atomic_add((int *)XLM_IRQ_NEST, -1);
1458 cebix 1.1 }
1459    
1460    
1461     /*
1462     * USR2 handler
1463     */
1464    
1465 gbeauche 1.8 #if EMULATED_PPC
1466     static void sigusr2_handler(int sig)
1467     {
1468     #if ASYNC_IRQ
1469     extern void HandleInterrupt(void);
1470     HandleInterrupt();
1471     #endif
1472     }
1473     #else
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     }