ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.34
Committed: 2004-05-15T11:07:11Z (20 years, 5 months ago) by gbeauche
Branch: MAIN
Changes since 1.33: +15 -6 lines
Log Message:
Fix bus frequency detection for more realistic timers.
Also add bus-frequency and timebase-frequency values to the Name Registry.

File Contents

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