ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.37
Committed: 2004-05-31T10:02:20Z (20 years, 5 months ago) by gbeauche
Branch: MAIN
Changes since 1.36: +10 -2 lines
Log Message:
Enable DR emulator with OldWorld ROMs too. It turned out that translated
code was also trying to access Serial memory.

Note however that I noticed some rare crashes with the DR emulator.
Probably caused by nested runs from EmulOps? We'd really want a native
68k emulator too for Execute68k() things.

File Contents

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