ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.39
Committed: 2004-06-17T05:15:25Z (20 years, 4 months ago) by gbeauche
Branch: MAIN
Changes since 1.38: +33 -0 lines
Log Message:
Get PVR information et al. through (slow) ioreg -c IOPlatformDevice

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