ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.40
Committed: 2004-06-22T12:20:17Z (20 years, 4 months ago) by gbeauche
Branch: MAIN
Changes since 1.39: +32 -13 lines
Log Message:
Improve timing of periodic threads (from Basilisk II), aka. make 10 seconds
really last 10 seconds, not 18. ;-)

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