ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.6
Committed: 2003-09-07T14:33:53Z (21 years, 2 months ago) by gbeauche
Branch: MAIN
Changes since 1.5: +27 -16 lines
Log Message:
- Integrate new NativeOp instructions to be used as trampolines to call
  native functions from ppc code.
- Little endian fixes in emul_op.cpp
- Add new 'gpch' 750 patch to workaround crash with MacOS 8.6
- Don't crash in Process Manager on reset/shutdown with MacOS 8.6
- We also have an experimental interrupt thread in emulation mode

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * main_unix.cpp - Emulation core, Unix implementation
3     *
4     * SheepShaver (C) 1997-2002 Christian Bauer and Marc Hellwig
5     *
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     * TODO:
69     * check if SIGSEGV handler works for all registers (including FP!)
70     */
71    
72     #include <unistd.h>
73     #include <fcntl.h>
74     #include <time.h>
75     #include <errno.h>
76     #include <stdio.h>
77     #include <stdlib.h>
78     #include <string.h>
79     #include <pthread.h>
80     #include <sys/mman.h>
81     #include <sys/ipc.h>
82     #include <sys/shm.h>
83     #include <signal.h>
84    
85     #include "sysdeps.h"
86     #include "main.h"
87     #include "version.h"
88     #include "prefs.h"
89     #include "prefs_editor.h"
90     #include "cpu_emulation.h"
91     #include "emul_op.h"
92     #include "xlowmem.h"
93     #include "xpram.h"
94     #include "timer.h"
95     #include "adb.h"
96     #include "sony.h"
97     #include "disk.h"
98     #include "cdrom.h"
99     #include "scsi.h"
100     #include "video.h"
101     #include "audio.h"
102     #include "ether.h"
103     #include "serial.h"
104     #include "clip.h"
105     #include "extfs.h"
106     #include "sys.h"
107     #include "macos_util.h"
108     #include "rom_patches.h"
109     #include "user_strings.h"
110 gbeauche 1.4 #include "vm_alloc.h"
111 gbeauche 1.5 #include "sigsegv.h"
112 cebix 1.1
113     #define DEBUG 0
114     #include "debug.h"
115    
116    
117     #include <X11/Xlib.h>
118    
119     #ifdef ENABLE_GTK
120     #include <gtk/gtk.h>
121     #endif
122    
123     #ifdef ENABLE_XF86_DGA
124     #include <X11/Xlib.h>
125     #include <X11/Xutil.h>
126     #include <X11/extensions/xf86dga.h>
127     #endif
128    
129     #ifdef ENABLE_MON
130     #include "mon.h"
131     #endif
132    
133    
134     // Enable Execute68k() safety checks?
135     #define SAFE_EXEC_68K 0
136    
137     // Interrupts in EMUL_OP mode?
138     #define INTERRUPTS_IN_EMUL_OP_MODE 1
139    
140     // Interrupts in native mode?
141     #define INTERRUPTS_IN_NATIVE_MODE 1
142    
143    
144     // Constants
145     const char ROM_FILE_NAME[] = "ROM";
146     const char ROM_FILE_NAME2[] = "Mac OS ROM";
147    
148     const uint32 ROM_AREA_SIZE = 0x500000; // Size of ROM area
149     const uint32 ROM_END = ROM_BASE + ROM_SIZE; // End of ROM
150    
151     const uint32 KERNEL_DATA_BASE = 0x68ffe000; // Address of Kernel Data
152     const uint32 KERNEL_DATA2_BASE = 0x5fffe000; // Alternate address of Kernel Data
153     const uint32 KERNEL_AREA_SIZE = 0x2000; // Size of Kernel Data area
154    
155     const uint32 SIG_STACK_SIZE = 0x10000; // Size of signal stack
156    
157    
158     // 68k Emulator Data
159     struct EmulatorData {
160     uint32 v[0x400];
161     };
162    
163    
164     // Kernel Data
165     struct KernelData {
166     uint32 v[0x400];
167     EmulatorData ed;
168     };
169    
170    
171     #if !EMULATED_PPC
172     // Structure in which registers are saved in a signal handler;
173     // sigcontext->regs points to it
174     // (see arch/ppc/kernel/signal.c)
175     typedef struct {
176     uint32 u[4];
177     } __attribute((aligned(16))) vector128;
178     #include <linux/elf.h>
179    
180     struct sigregs {
181     elf_gregset_t gp_regs; // Identical to pt_regs
182     double fp_regs[ELF_NFPREG]; // f0..f31 and fpsrc
183     //more (uninteresting) stuff following here
184     };
185     #endif
186    
187    
188     // Global variables (exported)
189     #if !EMULATED_PPC
190     void *TOC; // Small data pointer (r13)
191     #endif
192     uint32 RAMBase; // Base address of Mac RAM
193     uint32 RAMSize; // Size of Mac RAM
194     uint32 KernelDataAddr; // Address of Kernel Data
195     uint32 BootGlobsAddr; // Address of BootGlobs structure at top of Mac RAM
196     uint32 PVR; // Theoretical PVR
197     int64 CPUClockSpeed; // Processor clock speed (Hz)
198     int64 BusClockSpeed; // Bus clock speed (Hz)
199    
200    
201     // Global variables
202     static char *x_display_name = NULL; // X11 display name
203     Display *x_display = NULL; // X11 display handle
204    
205     static int zero_fd = 0; // FD of /dev/zero
206     static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
207     static int kernel_area = -1; // SHM ID of Kernel Data area
208     static bool rom_area_mapped = false; // Flag: Mac ROM mmap()ped
209     static bool ram_area_mapped = false; // Flag: Mac RAM mmap()ped
210     static void *mmap_RAMBase = NULL; // Base address of mmap()ed RAM area
211     static KernelData *kernel_data; // Pointer to Kernel Data
212     static EmulatorData *emulator_data;
213    
214     static uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes
215    
216     static bool nvram_thread_active = false; // Flag: NVRAM watchdog installed
217     static pthread_t nvram_thread; // NVRAM watchdog
218     static bool tick_thread_active = false; // Flag: MacOS thread installed
219     static pthread_t tick_thread; // 60Hz thread
220     static pthread_t emul_thread; // MacOS thread
221    
222     static bool ready_for_signals = false; // Handler installed, signals can be sent
223     static int64 num_segv = 0; // Number of handled SEGV signals
224    
225 gbeauche 1.6 static struct sigaction sigusr2_action; // Interrupt signal (of emulator thread)
226 cebix 1.1 #if !EMULATED_PPC
227     static struct sigaction sigsegv_action; // Data access exception signal (of emulator thread)
228     static struct sigaction sigill_action; // Illegal instruction signal (of emulator thread)
229     static void *sig_stack = NULL; // Stack for signal handlers
230     static void *extra_stack = NULL; // Stack for SIGSEGV inside interrupt handler
231     static bool emul_thread_fatal = false; // Flag: MacOS thread crashed, tick thread shall dump debug output
232     static sigregs sigsegv_regs; // Register dump when crashed
233     #endif
234    
235    
236     // Prototypes
237     static void Quit(void);
238     static void *emul_func(void *arg);
239     static void *nvram_func(void *arg);
240     static void *tick_func(void *arg);
241 gbeauche 1.6 static void sigusr2_handler(int sig, sigcontext_struct *sc);
242 cebix 1.1 #if !EMULATED_PPC
243     static void sigsegv_handler(int sig, sigcontext_struct *sc);
244     static void sigill_handler(int sig, sigcontext_struct *sc);
245     #endif
246    
247    
248     // From asm_linux.S
249     #if EMULATED_PPC
250     extern int atomic_add(int *var, int v);
251     extern int atomic_and(int *var, int v);
252     extern int atomic_or(int *var, int v);
253     #else
254     extern "C" void *get_toc(void);
255     extern "C" void *get_sp(void);
256     extern "C" void flush_icache_range(void *start, void *end);
257     extern "C" void jump_to_rom(uint32 entry, uint32 context);
258     extern "C" void quit_emulator(void);
259     extern "C" void execute_68k(uint32 pc, M68kRegisters *r);
260     extern "C" void ppc_interrupt(uint32 entry, uint32 kernel_data);
261     extern "C" int atomic_add(int *var, int v);
262     extern "C" int atomic_and(int *var, int v);
263     extern "C" int atomic_or(int *var, int v);
264     extern void paranoia_check(void);
265     #endif
266    
267    
268     /*
269     * Main program
270     */
271    
272     static void usage(const char *prg_name)
273     {
274     printf("Usage: %s [OPTION...]\n", prg_name);
275     printf("\nUnix options:\n");
276     printf(" --display STRING\n X display to use\n");
277     PrefsPrintUsage();
278     exit(0);
279     }
280    
281     int main(int argc, char **argv)
282     {
283     char str[256];
284     uint32 *boot_globs;
285     int16 i16;
286     int drive, driver;
287     int rom_fd;
288     FILE *proc_file;
289     const char *rom_path;
290     uint32 rom_size, actual;
291     uint8 *rom_tmp;
292     time_t now, expire;
293    
294     // Initialize variables
295     RAMBase = 0;
296     mmap_RAMBase = NULL;
297     tzset();
298    
299     // Print some info
300     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
301     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
302    
303     #if !EMULATED_PPC
304     // Get TOC pointer
305     TOC = get_toc();
306     #endif
307    
308     #ifdef ENABLE_GTK
309     // Init GTK
310     gtk_set_locale();
311     gtk_init(&argc, &argv);
312     #endif
313    
314     // Read preferences
315     PrefsInit(argc, argv);
316    
317     // Parse command line arguments
318     for (int i=1; i<argc; i++) {
319     if (strcmp(argv[i], "--help") == 0) {
320     usage(argv[0]);
321     } else if (strcmp(argv[i], "--display") == 0) {
322     i++;
323     if (i < argc)
324     x_display_name = strdup(argv[i]);
325     } else if (argv[i][0] == '-') {
326     fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
327     usage(argv[0]);
328     }
329     }
330    
331     // Open display
332     x_display = XOpenDisplay(x_display_name);
333     if (x_display == NULL) {
334     char str[256];
335     sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
336     ErrorAlert(str);
337     goto quit;
338     }
339    
340     #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
341     // Fork out, so we can return from fullscreen mode when things get ugly
342     XF86DGAForkApp(DefaultScreen(x_display));
343     #endif
344    
345     #ifdef ENABLE_MON
346     // Initialize mon
347     mon_init();
348     #endif
349    
350     // Get system info
351     PVR = 0x00040000; // Default: 604
352     CPUClockSpeed = 100000000; // Default: 100MHz
353     BusClockSpeed = 100000000; // Default: 100MHz
354     #if !EMULATED_PPC
355     proc_file = fopen("/proc/cpuinfo", "r");
356     if (proc_file) {
357     char line[256];
358     while(fgets(line, 255, proc_file)) {
359     // Read line
360     int len = strlen(line);
361     if (len == 0)
362     continue;
363     line[len-1] = 0;
364    
365     // Parse line
366     int i;
367     char value[256];
368     if (sscanf(line, "cpu : %s", value) == 1) {
369     if (strcmp(value, "601") == 0)
370     PVR = 0x00010000;
371     else if (strcmp(value, "603") == 0)
372     PVR = 0x00030000;
373     else if (strcmp(value, "604") == 0)
374     PVR = 0x00040000;
375     else if (strcmp(value, "603e") == 0)
376     PVR = 0x00060000;
377     else if (strcmp(value, "603ev") == 0)
378     PVR = 0x00070000;
379     else if (strcmp(value, "604e") == 0)
380     PVR = 0x00090000;
381     else if (strcmp(value, "604ev5") == 0)
382     PVR = 0x000a0000;
383     else if (strcmp(value, "750") == 0)
384     PVR = 0x00080000;
385     else if (strcmp(value, "821") == 0)
386     PVR = 0x00320000;
387     else if (strcmp(value, "860") == 0)
388     PVR = 0x00500000;
389     else
390     printf("WARNING: Unknown CPU type '%s', assuming 604\n", value);
391     }
392     if (sscanf(line, "clock : %dMHz", &i) == 1)
393     CPUClockSpeed = BusClockSpeed = i * 1000000;
394     }
395     fclose(proc_file);
396     } else {
397     sprintf(str, GetString(STR_PROC_CPUINFO_WARN), strerror(errno));
398     WarningAlert(str);
399     }
400     #endif
401     D(bug("PVR: %08x (assumed)\n", PVR));
402    
403     // Init system routines
404     SysInit();
405    
406     // Show preferences editor
407     if (!PrefsFindBool("nogui"))
408     if (!PrefsEditor())
409     goto quit;
410    
411     #if !EMULATED_PPC
412     // Check some things
413     paranoia_check();
414     #endif
415    
416     // Open /dev/zero
417     zero_fd = open("/dev/zero", O_RDWR);
418     if (zero_fd < 0) {
419     sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
420     ErrorAlert(str);
421     goto quit;
422     }
423    
424     // Create Low Memory area (0x0000..0x3000)
425 gbeauche 1.4 if (vm_acquire_fixed((char *)0, 0x3000) < 0) {
426 cebix 1.1 sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
427     ErrorAlert(str);
428     goto quit;
429     }
430     lm_area_mapped = true;
431    
432     // Create areas for Kernel Data
433     kernel_area = shmget(IPC_PRIVATE, KERNEL_AREA_SIZE, 0600);
434     if (kernel_area == -1) {
435     sprintf(str, GetString(STR_KD_SHMGET_ERR), strerror(errno));
436     ErrorAlert(str);
437     goto quit;
438     }
439     if (shmat(kernel_area, (void *)KERNEL_DATA_BASE, 0) < 0) {
440     sprintf(str, GetString(STR_KD_SHMAT_ERR), strerror(errno));
441     ErrorAlert(str);
442     goto quit;
443     }
444     if (shmat(kernel_area, (void *)KERNEL_DATA2_BASE, 0) < 0) {
445     sprintf(str, GetString(STR_KD2_SHMAT_ERR), strerror(errno));
446     ErrorAlert(str);
447     goto quit;
448     }
449     kernel_data = (KernelData *)0x68ffe000;
450     emulator_data = &kernel_data->ed;
451     KernelDataAddr = (uint32)kernel_data;
452     D(bug("Kernel Data at %p, Emulator Data at %p\n", kernel_data, emulator_data));
453    
454     // Create area for Mac ROM
455 gbeauche 1.4 if (vm_acquire_fixed((char *)ROM_BASE, ROM_AREA_SIZE) < 0) {
456 cebix 1.1 sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
457     ErrorAlert(str);
458     goto quit;
459     }
460 gbeauche 1.6 #if !EMULATED_PPC || defined(__powerpc__)
461 gbeauche 1.4 if (vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
462     sprintf(str, GetString(STR_ROM_MMAP_ERR), strerror(errno));
463     ErrorAlert(str);
464     goto quit;
465     }
466     #endif
467 cebix 1.1 rom_area_mapped = true;
468     D(bug("ROM area at %08x\n", ROM_BASE));
469    
470     // Create area for Mac RAM
471     RAMSize = PrefsFindInt32("ramsize");
472     if (RAMSize < 8*1024*1024) {
473     WarningAlert(GetString(STR_SMALL_RAM_WARN));
474     RAMSize = 8*1024*1024;
475     }
476    
477 gbeauche 1.4 mmap_RAMBase = (void *)0x20000000;
478     if (vm_acquire_fixed(mmap_RAMBase, RAMSize) < 0) {
479 cebix 1.1 sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
480     ErrorAlert(str);
481     goto quit;
482     }
483 gbeauche 1.4 #if !EMULATED_PPC
484     if (vm_protect(mmap_RAMBase, RAMSize, VM_PAGE_READ | VM_PAGE_WRITE | VM_PAGE_EXECUTE) < 0) {
485     sprintf(str, GetString(STR_RAM_MMAP_ERR), strerror(errno));
486     ErrorAlert(str);
487     goto quit;
488     }
489     #endif
490 cebix 1.1 RAMBase = (uint32)mmap_RAMBase;
491     ram_area_mapped = true;
492     D(bug("RAM area at %08x\n", RAMBase));
493    
494     if (RAMBase > ROM_BASE) {
495     ErrorAlert(GetString(STR_RAM_HIGHER_THAN_ROM_ERR));
496     goto quit;
497     }
498    
499     // Load Mac ROM
500     rom_path = PrefsFindString("rom");
501     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
502     if (rom_fd < 0) {
503     rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME2, O_RDONLY);
504     if (rom_fd < 0) {
505     ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
506     goto quit;
507     }
508     }
509     printf(GetString(STR_READING_ROM_FILE));
510     rom_size = lseek(rom_fd, 0, SEEK_END);
511     lseek(rom_fd, 0, SEEK_SET);
512     rom_tmp = new uint8[ROM_SIZE];
513     actual = read(rom_fd, (void *)rom_tmp, ROM_SIZE);
514     close(rom_fd);
515 gbeauche 1.3
516     // Decode Mac ROM
517     if (!DecodeROM(rom_tmp, actual)) {
518     if (rom_size != 4*1024*1024) {
519 cebix 1.1 ErrorAlert(GetString(STR_ROM_SIZE_ERR));
520     goto quit;
521     } else {
522     ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
523     goto quit;
524     }
525     }
526 gbeauche 1.3 delete[] rom_tmp;
527 cebix 1.1
528     // Load NVRAM
529     XPRAMInit();
530    
531     // Set boot volume
532     drive = PrefsFindInt32("bootdrive");
533     XPRAM[0x1378] = i16 >> 8;
534     XPRAM[0x1379] = i16 & 0xff;
535     driver = PrefsFindInt32("bootdriver");
536     XPRAM[0x137a] = i16 >> 8;
537     XPRAM[0x137b] = i16 & 0xff;
538    
539     // Create BootGlobs at top of Mac memory
540     memset((void *)(RAMBase + RAMSize - 4096), 0, 4096);
541     BootGlobsAddr = RAMBase + RAMSize - 0x1c;
542     boot_globs = (uint32 *)BootGlobsAddr;
543     boot_globs[-5] = htonl(RAMBase + RAMSize); // MemTop
544     boot_globs[0] = htonl(RAMBase); // First RAM bank
545     boot_globs[1] = htonl(RAMSize);
546     boot_globs[2] = htonl((uint32)-1); // End of bank table
547    
548     // Init drivers
549     SonyInit();
550     DiskInit();
551     CDROMInit();
552     SCSIInit();
553    
554     // Init external file system
555     ExtFSInit();
556    
557     // Init audio
558     AudioInit();
559    
560     // Init network
561     EtherInit();
562    
563     // Init serial ports
564     SerialInit();
565    
566     // Init Time Manager
567     TimerInit();
568    
569     // Init clipboard
570     ClipInit();
571    
572     // Init video
573     if (!VideoInit())
574     goto quit;
575    
576     // Install ROM patches
577     if (!PatchROM()) {
578     ErrorAlert(GetString(STR_UNSUPPORTED_ROM_TYPE_ERR));
579     goto quit;
580     }
581    
582     // Clear caches (as we loaded and patched code) and write protect ROM
583     #if !EMULATED_PPC
584     MakeExecutable(0, (void *)ROM_BASE, ROM_AREA_SIZE);
585     #endif
586 gbeauche 1.4 vm_protect((char *)ROM_BASE, ROM_AREA_SIZE, VM_PAGE_READ | VM_PAGE_EXECUTE);
587 cebix 1.1
588     // Initialize Kernel Data
589     memset(kernel_data, 0, sizeof(KernelData));
590     if (ROMType == ROMTYPE_NEWWORLD) {
591     static uint32 of_dev_tree[4] = {0, 0, 0, 0};
592     static uint8 vector_lookup_tbl[128];
593     static uint8 vector_mask_tbl[64];
594     memset((uint8 *)kernel_data + 0xb80, 0x3d, 0x80);
595     memset(vector_lookup_tbl, 0, 128);
596     memset(vector_mask_tbl, 0, 64);
597     kernel_data->v[0xb80 >> 2] = htonl(ROM_BASE);
598     kernel_data->v[0xb84 >> 2] = htonl((uint32)of_dev_tree); // OF device tree base
599     kernel_data->v[0xb90 >> 2] = htonl((uint32)vector_lookup_tbl);
600     kernel_data->v[0xb94 >> 2] = htonl((uint32)vector_mask_tbl);
601     kernel_data->v[0xb98 >> 2] = htonl(ROM_BASE); // OpenPIC base
602     kernel_data->v[0xbb0 >> 2] = htonl(0); // ADB base
603     kernel_data->v[0xc20 >> 2] = htonl(RAMSize);
604     kernel_data->v[0xc24 >> 2] = htonl(RAMSize);
605     kernel_data->v[0xc30 >> 2] = htonl(RAMSize);
606     kernel_data->v[0xc34 >> 2] = htonl(RAMSize);
607     kernel_data->v[0xc38 >> 2] = htonl(0x00010020);
608     kernel_data->v[0xc3c >> 2] = htonl(0x00200001);
609     kernel_data->v[0xc40 >> 2] = htonl(0x00010000);
610     kernel_data->v[0xc50 >> 2] = htonl(RAMBase);
611     kernel_data->v[0xc54 >> 2] = htonl(RAMSize);
612     kernel_data->v[0xf60 >> 2] = htonl(PVR);
613     kernel_data->v[0xf64 >> 2] = htonl(CPUClockSpeed);
614     kernel_data->v[0xf68 >> 2] = htonl(BusClockSpeed);
615     kernel_data->v[0xf6c >> 2] = htonl(CPUClockSpeed);
616     } else {
617     kernel_data->v[0xc80 >> 2] = htonl(RAMSize);
618     kernel_data->v[0xc84 >> 2] = htonl(RAMSize);
619     kernel_data->v[0xc90 >> 2] = htonl(RAMSize);
620     kernel_data->v[0xc94 >> 2] = htonl(RAMSize);
621     kernel_data->v[0xc98 >> 2] = htonl(0x00010020);
622     kernel_data->v[0xc9c >> 2] = htonl(0x00200001);
623     kernel_data->v[0xca0 >> 2] = htonl(0x00010000);
624     kernel_data->v[0xcb0 >> 2] = htonl(RAMBase);
625     kernel_data->v[0xcb4 >> 2] = htonl(RAMSize);
626     kernel_data->v[0xf80 >> 2] = htonl(PVR);
627     kernel_data->v[0xf84 >> 2] = htonl(CPUClockSpeed);
628     kernel_data->v[0xf88 >> 2] = htonl(BusClockSpeed);
629     kernel_data->v[0xf8c >> 2] = htonl(CPUClockSpeed);
630     }
631    
632     // Initialize extra low memory
633     D(bug("Initializing Low Memory...\n"));
634     memset(NULL, 0, 0x3000);
635     WriteMacInt32(XLM_SIGNATURE, FOURCC('B','a','a','h')); // Signature to detect SheepShaver
636     WriteMacInt32(XLM_KERNEL_DATA, (uint32)kernel_data); // For trap replacement routines
637     WriteMacInt32(XLM_PVR, PVR); // Theoretical PVR
638     WriteMacInt32(XLM_BUS_CLOCK, BusClockSpeed); // For DriverServicesLib patch
639     WriteMacInt16(XLM_EXEC_RETURN_OPCODE, M68K_EXEC_RETURN); // For Execute68k() (RTS from the executed 68k code will jump here and end 68k mode)
640 gbeauche 1.6 #if EMULATED_PPC
641     WriteMacInt32(XLM_ETHER_INIT, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_INIT));
642     WriteMacInt32(XLM_ETHER_TERM, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_TERM));
643     WriteMacInt32(XLM_ETHER_OPEN, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_OPEN));
644     WriteMacInt32(XLM_ETHER_CLOSE, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_CLOSE));
645     WriteMacInt32(XLM_ETHER_WPUT, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_WPUT));
646     WriteMacInt32(XLM_ETHER_RSRV, POWERPC_NATIVE_OP_FUNC(NATIVE_ETHER_RSRV));
647     WriteMacInt32(XLM_VIDEO_DOIO, POWERPC_NATIVE_OP_FUNC(NATIVE_VIDEO_DO_DRIVER_IO));
648     #else
649 cebix 1.1 WriteMacInt32(XLM_TOC, (uint32)TOC); // TOC pointer of emulator
650     WriteMacInt32(XLM_ETHER_INIT, (uint32)InitStreamModule); // DLPI ethernet driver functions
651     WriteMacInt32(XLM_ETHER_TERM, (uint32)TerminateStreamModule);
652     WriteMacInt32(XLM_ETHER_OPEN, (uint32)ether_open);
653     WriteMacInt32(XLM_ETHER_CLOSE, (uint32)ether_close);
654     WriteMacInt32(XLM_ETHER_WPUT, (uint32)ether_wput);
655     WriteMacInt32(XLM_ETHER_RSRV, (uint32)ether_rsrv);
656     WriteMacInt32(XLM_VIDEO_DOIO, (uint32)VideoDoDriverIO);
657     #endif
658     D(bug("Low Memory initialized\n"));
659    
660     // Start 60Hz thread
661     tick_thread_active = (pthread_create(&tick_thread, NULL, tick_func, NULL) == 0);
662     D(bug("Tick thread installed (%ld)\n", tick_thread));
663    
664     // Start NVRAM watchdog thread
665     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
666     nvram_thread_active = (pthread_create(&nvram_thread, NULL, nvram_func, NULL) == 0);
667     D(bug("NVRAM thread installed (%ld)\n", nvram_thread));
668    
669     #if !EMULATED_PPC
670     // Create and install stacks for signal handlers
671     sig_stack = malloc(SIG_STACK_SIZE);
672     D(bug("Signal stack at %p\n", sig_stack));
673     if (sig_stack == NULL) {
674     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
675     goto quit;
676     }
677     extra_stack = malloc(SIG_STACK_SIZE);
678     D(bug("Extra stack at %p\n", extra_stack));
679     if (extra_stack == NULL) {
680     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
681     goto quit;
682     }
683     struct sigaltstack new_stack;
684     new_stack.ss_sp = sig_stack;
685     new_stack.ss_flags = 0;
686     new_stack.ss_size = SIG_STACK_SIZE;
687     if (sigaltstack(&new_stack, NULL) < 0) {
688     sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
689     ErrorAlert(str);
690     goto quit;
691     }
692     #endif
693    
694     #if !EMULATED_PPC
695     // Install SIGSEGV handler
696     sigemptyset(&sigsegv_action.sa_mask); // Block interrupts during SEGV handling
697     sigaddset(&sigsegv_action.sa_mask, SIGUSR2);
698     sigsegv_action.sa_handler = (__sighandler_t)sigsegv_handler;
699     sigsegv_action.sa_flags = SA_ONSTACK;
700     sigsegv_action.sa_restorer = NULL;
701     if (sigaction(SIGSEGV, &sigsegv_action, NULL) < 0) {
702     sprintf(str, GetString(STR_SIGSEGV_INSTALL_ERR), strerror(errno));
703     ErrorAlert(str);
704     goto quit;
705     }
706    
707     // Install SIGILL handler
708     sigemptyset(&sigill_action.sa_mask); // Block interrupts during ILL handling
709     sigaddset(&sigill_action.sa_mask, SIGUSR2);
710     sigill_action.sa_handler = (__sighandler_t)sigill_handler;
711     sigill_action.sa_flags = SA_ONSTACK;
712     sigill_action.sa_restorer = NULL;
713     if (sigaction(SIGILL, &sigill_action, NULL) < 0) {
714     sprintf(str, GetString(STR_SIGILL_INSTALL_ERR), strerror(errno));
715     ErrorAlert(str);
716     goto quit;
717     }
718 gbeauche 1.6 #endif
719 cebix 1.1
720     // Install interrupt signal handler
721     sigemptyset(&sigusr2_action.sa_mask);
722     sigusr2_action.sa_handler = (__sighandler_t)sigusr2_handler;
723 gbeauche 1.6 sigusr2_action.sa_flags = 0;
724     #if !EMULATED_PPC
725 cebix 1.1 sigusr2_action.sa_flags = SA_ONSTACK | SA_RESTART;
726 gbeauche 1.6 #endif
727 cebix 1.1 sigusr2_action.sa_restorer = NULL;
728     if (sigaction(SIGUSR2, &sigusr2_action, NULL) < 0) {
729     sprintf(str, GetString(STR_SIGUSR2_INSTALL_ERR), strerror(errno));
730     ErrorAlert(str);
731     goto quit;
732     }
733    
734     // Get my thread ID and execute MacOS thread function
735     emul_thread = pthread_self();
736     D(bug("MacOS thread is %ld\n", emul_thread));
737     emul_func(NULL);
738    
739     quit:
740     Quit();
741     return 0;
742     }
743    
744    
745     /*
746     * Cleanup and quit
747     */
748    
749     static void Quit(void)
750     {
751     // Stop 60Hz thread
752     if (tick_thread_active) {
753     pthread_cancel(tick_thread);
754     pthread_join(tick_thread, NULL);
755     }
756    
757     // Stop NVRAM watchdog thread
758     if (nvram_thread_active) {
759     pthread_cancel(nvram_thread);
760     pthread_join(nvram_thread, NULL);
761     }
762    
763     #if !EMULATED_PPC
764     // Uninstall SIGSEGV handler
765     sigemptyset(&sigsegv_action.sa_mask);
766     sigsegv_action.sa_handler = SIG_DFL;
767     sigsegv_action.sa_flags = 0;
768     sigaction(SIGSEGV, &sigsegv_action, NULL);
769    
770     // Uninstall SIGILL handler
771     sigemptyset(&sigill_action.sa_mask);
772     sigill_action.sa_handler = SIG_DFL;
773     sigill_action.sa_flags = 0;
774     sigaction(SIGILL, &sigill_action, NULL);
775     #endif
776    
777     // Save NVRAM
778     XPRAMExit();
779    
780     // Exit clipboard
781     ClipExit();
782    
783     // Exit Time Manager
784     TimerExit();
785    
786     // Exit serial
787     SerialExit();
788    
789     // Exit network
790     EtherExit();
791    
792     // Exit audio
793     AudioExit();
794    
795     // Exit video
796     VideoExit();
797    
798     // Exit external file system
799     ExtFSExit();
800    
801     // Exit drivers
802     SCSIExit();
803     CDROMExit();
804     DiskExit();
805     SonyExit();
806    
807     // Delete RAM area
808     if (ram_area_mapped)
809 gbeauche 1.4 vm_release(mmap_RAMBase, RAMSize);
810 cebix 1.1
811     // Delete ROM area
812     if (rom_area_mapped)
813 gbeauche 1.4 vm_release((char *)ROM_BASE, ROM_AREA_SIZE);
814 cebix 1.1
815     // Delete Kernel Data area
816     if (kernel_area >= 0) {
817     shmdt((void *)KERNEL_DATA_BASE);
818     shmdt((void *)KERNEL_DATA2_BASE);
819     shmctl(kernel_area, IPC_RMID, NULL);
820     }
821    
822     // Delete Low Memory area
823     if (lm_area_mapped)
824     munmap((char *)0x0000, 0x3000);
825    
826     // Close /dev/zero
827     if (zero_fd > 0)
828     close(zero_fd);
829    
830     // Exit system routines
831     SysExit();
832    
833     // Exit preferences
834     PrefsExit();
835    
836     #ifdef ENABLE_MON
837     // Exit mon
838     mon_exit();
839     #endif
840    
841     // Close X11 server connection
842     if (x_display)
843     XCloseDisplay(x_display);
844    
845     exit(0);
846     }
847    
848    
849     /*
850     * Jump into Mac ROM, start 680x0 emulator
851     */
852    
853     #if EMULATED_PPC
854     extern void emul_ppc(uint32 start);
855     extern void init_emul_ppc(void);
856     void jump_to_rom(uint32 entry)
857     {
858     init_emul_ppc();
859     emul_ppc(entry);
860     }
861     #endif
862    
863    
864     /*
865     * Emulator thread function
866     */
867    
868     static void *emul_func(void *arg)
869     {
870     // We're now ready to receive signals
871     ready_for_signals = true;
872    
873     // Decrease priority, so more time-critical things like audio will work better
874     nice(1);
875    
876     // Jump to ROM boot routine
877     D(bug("Jumping to ROM\n"));
878     #if EMULATED_PPC
879     jump_to_rom(ROM_BASE + 0x310000);
880     #else
881     jump_to_rom(ROM_BASE + 0x310000, (uint32)emulator_data);
882     #endif
883     D(bug("Returned from ROM\n"));
884    
885     // We're no longer ready to receive signals
886     ready_for_signals = false;
887     return NULL;
888     }
889    
890    
891     #if !EMULATED_PPC
892     /*
893     * Execute 68k subroutine (must be ended with RTS)
894     * This must only be called by the emul_thread when in EMUL_OP mode
895     * r->a[7] is unused, the routine runs on the caller's stack
896     */
897    
898     void Execute68k(uint32 pc, M68kRegisters *r)
899     {
900     #if SAFE_EXEC_68K
901     if (ReadMacInt32(XLM_RUN_MODE) != MODE_EMUL_OP)
902     printf("FATAL: Execute68k() not called from EMUL_OP mode\n");
903     if (!pthread_equal(pthread_self(), emul_thread))
904     printf("FATAL: Execute68k() not called from emul_thread\n");
905     #endif
906     execute_68k(pc, r);
907     }
908    
909    
910     /*
911     * Execute 68k A-Trap from EMUL_OP routine
912     * r->a[7] is unused, the routine runs on the caller's stack
913     */
914    
915     void Execute68kTrap(uint16 trap, M68kRegisters *r)
916     {
917     uint16 proc[2] = {trap, M68K_RTS};
918     Execute68k((uint32)proc, r);
919     }
920     #endif
921    
922    
923     /*
924     * Execute PPC code from EMUL_OP routine (real mode switch)
925     */
926    
927     void ExecutePPC(void (*func)())
928     {
929     uint32 tvect[2] = {(uint32)func, 0}; // Fake TVECT
930     RoutineDescriptor desc = BUILD_PPC_ROUTINE_DESCRIPTOR(0, tvect);
931     M68kRegisters r;
932     Execute68k((uint32)&desc, &r);
933     }
934    
935    
936     /*
937     * Quit emulator (cause return from jump_to_rom)
938     */
939    
940     void QuitEmulator(void)
941     {
942     #if EMULATED_PPC
943     Quit();
944     #else
945     quit_emulator();
946     #endif
947     }
948    
949    
950     /*
951     * Pause/resume emulator
952     */
953    
954     void PauseEmulator(void)
955     {
956     pthread_kill(emul_thread, SIGSTOP);
957     }
958    
959     void ResumeEmulator(void)
960     {
961     pthread_kill(emul_thread, SIGCONT);
962     }
963    
964    
965     /*
966     * Dump 68k registers
967     */
968    
969     void Dump68kRegs(M68kRegisters *r)
970     {
971     // Display 68k registers
972     for (int i=0; i<8; i++) {
973     printf("d%d: %08x", i, r->d[i]);
974     if (i == 3 || i == 7)
975     printf("\n");
976     else
977     printf(", ");
978     }
979     for (int i=0; i<8; i++) {
980     printf("a%d: %08x", i, r->a[i]);
981     if (i == 3 || i == 7)
982     printf("\n");
983     else
984     printf(", ");
985     }
986     }
987    
988    
989     /*
990     * Make code executable
991     */
992    
993     void MakeExecutable(int dummy, void *start, uint32 length)
994     {
995     #if !EMULATED_PPC
996     if (((uint32)start >= ROM_BASE) && ((uint32)start < (ROM_BASE + ROM_SIZE)))
997     return;
998     flush_icache_range(start, (void *)((uint32)start + length));
999     #endif
1000     }
1001    
1002    
1003     /*
1004     * Patch things after system startup (gets called by disk driver accRun routine)
1005     */
1006    
1007     void PatchAfterStartup(void)
1008     {
1009 gbeauche 1.6 #if EMULATED_PPC
1010     ExecuteNative(NATIVE_VIDEO_INSTALL_ACCEL);
1011     #else
1012 cebix 1.1 ExecutePPC(VideoInstallAccel);
1013 gbeauche 1.6 #endif
1014 cebix 1.1 InstallExtFS();
1015     }
1016    
1017    
1018     /*
1019     * NVRAM watchdog thread (saves NVRAM every minute)
1020     */
1021    
1022     static void *nvram_func(void *arg)
1023     {
1024     struct timespec req = {60, 0}; // 1 minute
1025    
1026     for (;;) {
1027     pthread_testcancel();
1028     nanosleep(&req, NULL);
1029     pthread_testcancel();
1030     if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
1031     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
1032     SaveXPRAM();
1033     }
1034     }
1035     return NULL;
1036     }
1037    
1038    
1039     /*
1040     * 60Hz thread (really 60.15Hz)
1041     */
1042    
1043     static void *tick_func(void *arg)
1044     {
1045     int tick_counter = 0;
1046     struct timespec req = {0, 16625000};
1047    
1048     for (;;) {
1049    
1050     // Wait
1051     nanosleep(&req, NULL);
1052    
1053     #if !EMULATED_PPC
1054     // Did we crash?
1055     if (emul_thread_fatal) {
1056    
1057     // Yes, dump registers
1058     pt_regs *r = (pt_regs *)&sigsegv_regs;
1059     char str[256];
1060     sprintf(str, "SIGSEGV\n"
1061     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1062     " xer %08lx cr %08lx \n"
1063     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1064     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1065     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1066     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1067     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1068     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1069     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1070     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1071     r->nip, r->link, r->ctr, r->msr,
1072     r->xer, r->ccr,
1073     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1074     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1075     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1076     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1077     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1078     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1079     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1080     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1081     printf(str);
1082     VideoQuitFullScreen();
1083    
1084     #ifdef ENABLE_MON
1085     // Start up mon in real-mode
1086     printf("Welcome to the sheep factory.\n");
1087     char *arg[4] = {"mon", "-m", "-r", NULL};
1088     mon(3, arg);
1089     #endif
1090     return NULL;
1091     }
1092     #endif
1093    
1094     // Pseudo Mac 1Hz interrupt, update local time
1095     if (++tick_counter > 60) {
1096     tick_counter = 0;
1097     WriteMacInt32(0x20c, TimerDateTime());
1098     }
1099    
1100     // Trigger 60Hz interrupt
1101     if (ReadMacInt32(XLM_IRQ_NEST) == 0) {
1102     SetInterruptFlag(INTFLAG_VIA);
1103     TriggerInterrupt();
1104     }
1105     }
1106     return NULL;
1107     }
1108    
1109    
1110     /*
1111 cebix 1.2 * Pthread configuration
1112     */
1113    
1114     void Set_pthread_attr(pthread_attr_t *attr, int priority)
1115     {
1116     // nothing to do
1117     }
1118    
1119    
1120     /*
1121 cebix 1.1 * Mutexes
1122     */
1123    
1124     struct B2_mutex {
1125     int dummy;
1126     };
1127    
1128     B2_mutex *B2_create_mutex(void)
1129     {
1130     return new B2_mutex;
1131     }
1132    
1133     void B2_lock_mutex(B2_mutex *mutex)
1134     {
1135     }
1136    
1137     void B2_unlock_mutex(B2_mutex *mutex)
1138     {
1139     }
1140    
1141     void B2_delete_mutex(B2_mutex *mutex)
1142     {
1143     delete mutex;
1144     }
1145    
1146    
1147     /*
1148     * Trigger signal USR2 from another thread
1149     */
1150    
1151     void TriggerInterrupt(void)
1152     {
1153     if (ready_for_signals)
1154     pthread_kill(emul_thread, SIGUSR2);
1155     }
1156    
1157    
1158     /*
1159     * Interrupt flags (must be handled atomically!)
1160     */
1161    
1162     volatile uint32 InterruptFlags = 0;
1163    
1164     void SetInterruptFlag(uint32 flag)
1165     {
1166     atomic_or((int *)&InterruptFlags, flag);
1167     }
1168    
1169     void ClearInterruptFlag(uint32 flag)
1170     {
1171     atomic_and((int *)&InterruptFlags, ~flag);
1172     }
1173    
1174    
1175     /*
1176     * Disable interrupts
1177     */
1178    
1179     void DisableInterrupt(void)
1180     {
1181 gbeauche 1.6 atomic_add((int *)XLM_IRQ_NEST, tswap32(1));
1182 cebix 1.1 }
1183    
1184    
1185     /*
1186     * Enable interrupts
1187     */
1188    
1189     void EnableInterrupt(void)
1190     {
1191 gbeauche 1.6 atomic_add((int *)XLM_IRQ_NEST, tswap32((uint32)-1));
1192 cebix 1.1 }
1193    
1194    
1195     /*
1196     * USR2 handler
1197     */
1198    
1199     static void sigusr2_handler(int sig, sigcontext_struct *sc)
1200     {
1201 gbeauche 1.6 #if EMULATED_PPC
1202     HandleInterrupt();
1203     #else
1204 cebix 1.1 pt_regs *r = sc->regs;
1205    
1206     // Do nothing if interrupts are disabled
1207     if (*(int32 *)XLM_IRQ_NEST > 0)
1208     return;
1209    
1210     // Disable MacOS stack sniffer
1211     WriteMacInt32(0x110, 0);
1212    
1213     // Interrupt action depends on current run mode
1214     switch (ReadMacInt32(XLM_RUN_MODE)) {
1215     case MODE_68K:
1216     // 68k emulator active, trigger 68k interrupt level 1
1217     WriteMacInt16(ntohl(kernel_data->v[0x67c >> 2]), 1);
1218     r->ccr |= ntohl(kernel_data->v[0x674 >> 2]);
1219     break;
1220    
1221     #if INTERRUPTS_IN_NATIVE_MODE
1222     case MODE_NATIVE:
1223     // 68k emulator inactive, in nanokernel?
1224     if (r->gpr[1] != KernelDataAddr) {
1225     // Prepare for 68k interrupt level 1
1226     WriteMacInt16(ntohl(kernel_data->v[0x67c >> 2]), 1);
1227     WriteMacInt32(ntohl(kernel_data->v[0x658 >> 2]) + 0xdc, ReadMacInt32(ntohl(kernel_data->v[0x658 >> 2]) + 0xdc) | ntohl(kernel_data->v[0x674 >> 2]));
1228    
1229     // Execute nanokernel interrupt routine (this will activate the 68k emulator)
1230     atomic_add((int32 *)XLM_IRQ_NEST, 1);
1231     if (ROMType == ROMTYPE_NEWWORLD)
1232     ppc_interrupt(ROM_BASE + 0x312b1c, KernelDataAddr);
1233     else
1234     ppc_interrupt(ROM_BASE + 0x312a3c, KernelDataAddr);
1235     }
1236     break;
1237     #endif
1238    
1239     #if INTERRUPTS_IN_EMUL_OP_MODE
1240     case MODE_EMUL_OP:
1241     // 68k emulator active, within EMUL_OP routine, execute 68k interrupt routine directly when interrupt level is 0
1242     if ((ReadMacInt32(XLM_68K_R25) & 7) == 0) {
1243    
1244     // Set extra stack for SIGSEGV handler
1245     struct sigaltstack new_stack;
1246     new_stack.ss_sp = extra_stack;
1247     new_stack.ss_flags = 0;
1248     new_stack.ss_size = SIG_STACK_SIZE;
1249     sigaltstack(&new_stack, NULL);
1250     #if 1
1251     // Execute full 68k interrupt routine
1252     M68kRegisters r;
1253     uint32 old_r25 = ReadMacInt32(XLM_68K_R25); // Save interrupt level
1254     WriteMacInt32(XLM_68K_R25, 0x21); // Execute with interrupt level 1
1255     static const uint16 proc[] = {
1256     0x3f3c, 0x0000, // move.w #$0000,-(sp) (fake format word)
1257     0x487a, 0x000a, // pea @1(pc) (return address)
1258     0x40e7, // move sr,-(sp) (saved SR)
1259     0x2078, 0x0064, // move.l $64,a0
1260     0x4ed0, // jmp (a0)
1261     M68K_RTS // @1
1262     };
1263     Execute68k((uint32)proc, &r);
1264     WriteMacInt32(XLM_68K_R25, old_r25); // Restore interrupt level
1265     #else
1266     // Only update cursor
1267     if (HasMacStarted()) {
1268     if (InterruptFlags & INTFLAG_VIA) {
1269     ClearInterruptFlag(INTFLAG_VIA);
1270     ADBInterrupt();
1271     ExecutePPC(VideoVBL);
1272     }
1273     }
1274     #endif
1275     // Reset normal signal stack
1276     new_stack.ss_sp = sig_stack;
1277     new_stack.ss_flags = 0;
1278     new_stack.ss_size = SIG_STACK_SIZE;
1279     sigaltstack(&new_stack, NULL);
1280     }
1281     break;
1282     #endif
1283    
1284     }
1285 gbeauche 1.6 #endif
1286 cebix 1.1 }
1287    
1288    
1289 gbeauche 1.6 #if !EMULATED_PPC
1290 cebix 1.1 /*
1291     * SIGSEGV handler
1292     */
1293    
1294     static void sigsegv_handler(int sig, sigcontext_struct *sc)
1295     {
1296     pt_regs *r = sc->regs;
1297 gbeauche 1.5
1298     // Get effective address
1299     uint32 addr = r->dar;
1300    
1301     #if ENABLE_VOSF
1302     // Handle screen fault.
1303     extern bool Screen_fault_handler(sigsegv_address_t fault_address, sigsegv_address_t fault_instruction);
1304     if (Screen_fault_handler((sigsegv_address_t)addr, (sigsegv_address_t)r->nip))
1305     return;
1306     #endif
1307    
1308 cebix 1.1 num_segv++;
1309    
1310     // Fault in Mac ROM or RAM?
1311     bool mac_fault = (r->nip >= ROM_BASE) && (r->nip < (ROM_BASE + ROM_AREA_SIZE)) || (r->nip >= RAMBase) && (r->nip < (RAMBase + RAMSize));
1312     if (mac_fault) {
1313    
1314     // "VM settings" during MacOS 8 installation
1315     if (r->nip == ROM_BASE + 0x488160 && r->gpr[20] == 0xf8000000) {
1316     r->nip += 4;
1317     r->gpr[8] = 0;
1318     return;
1319    
1320     // MacOS 8.5 installation
1321     } else if (r->nip == ROM_BASE + 0x488140 && r->gpr[16] == 0xf8000000) {
1322     r->nip += 4;
1323     r->gpr[8] = 0;
1324     return;
1325    
1326     // MacOS 8 serial drivers on startup
1327     } else if (r->nip == ROM_BASE + 0x48e080 && (r->gpr[8] == 0xf3012002 || r->gpr[8] == 0xf3012000)) {
1328     r->nip += 4;
1329     r->gpr[8] = 0;
1330     return;
1331    
1332     // MacOS 8.1 serial drivers on startup
1333     } else if (r->nip == ROM_BASE + 0x48c5e0 && (r->gpr[20] == 0xf3012002 || r->gpr[20] == 0xf3012000)) {
1334     r->nip += 4;
1335     return;
1336     } else if (r->nip == ROM_BASE + 0x4a10a0 && (r->gpr[20] == 0xf3012002 || r->gpr[20] == 0xf3012000)) {
1337     r->nip += 4;
1338     return;
1339     }
1340    
1341 gbeauche 1.5 // Get opcode and divide into fields
1342     uint32 opcode = *((uint32 *)r->nip);
1343     uint32 primop = opcode >> 26;
1344     uint32 exop = (opcode >> 1) & 0x3ff;
1345     uint32 ra = (opcode >> 16) & 0x1f;
1346     uint32 rb = (opcode >> 11) & 0x1f;
1347     uint32 rd = (opcode >> 21) & 0x1f;
1348     int32 imm = (int16)(opcode & 0xffff);
1349    
1350 cebix 1.1 // Analyze opcode
1351     enum {
1352     TYPE_UNKNOWN,
1353     TYPE_LOAD,
1354     TYPE_STORE
1355     } transfer_type = TYPE_UNKNOWN;
1356     enum {
1357     SIZE_UNKNOWN,
1358     SIZE_BYTE,
1359     SIZE_HALFWORD,
1360     SIZE_WORD
1361     } transfer_size = SIZE_UNKNOWN;
1362     enum {
1363     MODE_UNKNOWN,
1364     MODE_NORM,
1365     MODE_U,
1366     MODE_X,
1367     MODE_UX
1368     } addr_mode = MODE_UNKNOWN;
1369     switch (primop) {
1370     case 31:
1371     switch (exop) {
1372     case 23: // lwzx
1373     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
1374     case 55: // lwzux
1375     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
1376     case 87: // lbzx
1377     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
1378     case 119: // lbzux
1379     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
1380     case 151: // stwx
1381     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
1382     case 183: // stwux
1383     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
1384     case 215: // stbx
1385     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
1386     case 247: // stbux
1387     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
1388     case 279: // lhzx
1389     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1390     case 311: // lhzux
1391     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1392     case 343: // lhax
1393     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1394     case 375: // lhaux
1395     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1396     case 407: // sthx
1397     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_X; break;
1398     case 439: // sthux
1399     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_UX; break;
1400     }
1401     break;
1402    
1403     case 32: // lwz
1404     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
1405     case 33: // lwzu
1406     transfer_type = TYPE_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
1407     case 34: // lbz
1408     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
1409     case 35: // lbzu
1410     transfer_type = TYPE_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
1411     case 36: // stw
1412     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
1413     case 37: // stwu
1414     transfer_type = TYPE_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
1415     case 38: // stb
1416     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
1417     case 39: // stbu
1418     transfer_type = TYPE_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
1419     case 40: // lhz
1420     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1421     case 41: // lhzu
1422     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1423     case 42: // lha
1424     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1425     case 43: // lhau
1426     transfer_type = TYPE_LOAD; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1427     case 44: // sth
1428     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_NORM; break;
1429     case 45: // sthu
1430     transfer_type = TYPE_STORE; transfer_size = SIZE_HALFWORD; addr_mode = MODE_U; break;
1431     }
1432    
1433     // Ignore ROM writes
1434     if (transfer_type == TYPE_STORE && addr >= ROM_BASE && addr < ROM_BASE + ROM_SIZE) {
1435     // 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->nip));
1436     if (addr_mode == MODE_U || addr_mode == MODE_UX)
1437     r->gpr[ra] = addr;
1438     r->nip += 4;
1439     goto rti;
1440     }
1441    
1442     // Ignore illegal memory accesses?
1443     if (PrefsFindBool("ignoresegv")) {
1444     if (addr_mode == MODE_U || addr_mode == MODE_UX)
1445     r->gpr[ra] = addr;
1446     if (transfer_type == TYPE_LOAD)
1447     r->gpr[rd] = 0;
1448     r->nip += 4;
1449     goto rti;
1450     }
1451    
1452     // In GUI mode, show error alert
1453     if (!PrefsFindBool("nogui")) {
1454     char str[256];
1455     if (transfer_type == TYPE_LOAD || transfer_type == TYPE_STORE)
1456     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->nip, r->gpr[24], r->gpr[1]);
1457     else
1458     sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->nip, r->gpr[24], r->gpr[1], opcode);
1459     ErrorAlert(str);
1460     QuitEmulator();
1461     return;
1462     }
1463     }
1464    
1465     // For all other errors, jump into debugger (sort of...)
1466     if (!ready_for_signals) {
1467     printf("SIGSEGV\n");
1468     printf(" sigcontext %p, pt_regs %p\n", sc, r);
1469     printf(
1470     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1471     " xer %08lx cr %08lx \n"
1472     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1473     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1474     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1475     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1476     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1477     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1478     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1479     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1480     r->nip, r->link, r->ctr, r->msr,
1481     r->xer, r->ccr,
1482     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1483     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1484     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1485     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1486     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1487     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1488     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1489     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1490     exit(1);
1491     QuitEmulator();
1492     return;
1493     } else {
1494     // We crashed. Save registers, tell tick thread and loop forever
1495     sigsegv_regs = *(sigregs *)r;
1496     emul_thread_fatal = true;
1497     for (;;) ;
1498     }
1499     rti:;
1500     }
1501    
1502    
1503     /*
1504     * SIGILL handler
1505     */
1506    
1507     static void sigill_handler(int sig, sigcontext_struct *sc)
1508     {
1509     pt_regs *r = sc->regs;
1510     char str[256];
1511    
1512     // Fault in Mac ROM or RAM?
1513     bool mac_fault = (r->nip >= ROM_BASE) && (r->nip < (ROM_BASE + ROM_AREA_SIZE)) || (r->nip >= RAMBase) && (r->nip < (RAMBase + RAMSize));
1514     if (mac_fault) {
1515    
1516     // Get opcode and divide into fields
1517     uint32 opcode = *((uint32 *)r->nip);
1518     uint32 primop = opcode >> 26;
1519     uint32 exop = (opcode >> 1) & 0x3ff;
1520     uint32 ra = (opcode >> 16) & 0x1f;
1521     uint32 rb = (opcode >> 11) & 0x1f;
1522     uint32 rd = (opcode >> 21) & 0x1f;
1523     int32 imm = (int16)(opcode & 0xffff);
1524    
1525     switch (primop) {
1526     case 9: // POWER instructions
1527     case 22:
1528     power_inst: sprintf(str, GetString(STR_POWER_INSTRUCTION_ERR), r->nip, r->gpr[1], opcode);
1529     ErrorAlert(str);
1530     QuitEmulator();
1531     return;
1532    
1533     case 31:
1534     switch (exop) {
1535     case 83: // mfmsr
1536     r->gpr[rd] = 0xf072;
1537     r->nip += 4;
1538     goto rti;
1539    
1540     case 210: // mtsr
1541     case 242: // mtsrin
1542     case 306: // tlbie
1543     r->nip += 4;
1544     goto rti;
1545    
1546     case 339: { // mfspr
1547     int spr = ra | (rb << 5);
1548     switch (spr) {
1549     case 0: // MQ
1550     case 22: // DEC
1551     case 952: // MMCR0
1552     case 953: // PMC1
1553     case 954: // PMC2
1554     case 955: // SIA
1555     case 956: // MMCR1
1556     case 957: // PMC3
1557     case 958: // PMC4
1558     case 959: // SDA
1559     r->nip += 4;
1560     goto rti;
1561     case 25: // SDR1
1562     r->gpr[rd] = 0xdead001f;
1563     r->nip += 4;
1564     goto rti;
1565     case 287: // PVR
1566     r->gpr[rd] = PVR;
1567     r->nip += 4;
1568     goto rti;
1569     }
1570     break;
1571     }
1572    
1573     case 467: { // mtspr
1574     int spr = ra | (rb << 5);
1575     switch (spr) {
1576     case 0: // MQ
1577     case 22: // DEC
1578     case 275: // SPRG3
1579     case 528: // IBAT0U
1580     case 529: // IBAT0L
1581     case 530: // IBAT1U
1582     case 531: // IBAT1L
1583     case 532: // IBAT2U
1584     case 533: // IBAT2L
1585     case 534: // IBAT3U
1586     case 535: // IBAT3L
1587     case 536: // DBAT0U
1588     case 537: // DBAT0L
1589     case 538: // DBAT1U
1590     case 539: // DBAT1L
1591     case 540: // DBAT2U
1592     case 541: // DBAT2L
1593     case 542: // DBAT3U
1594     case 543: // DBAT3L
1595     case 952: // MMCR0
1596     case 953: // PMC1
1597     case 954: // PMC2
1598     case 955: // SIA
1599     case 956: // MMCR1
1600     case 957: // PMC3
1601     case 958: // PMC4
1602     case 959: // SDA
1603     r->nip += 4;
1604     goto rti;
1605     }
1606     break;
1607     }
1608    
1609     case 29: case 107: case 152: case 153: // POWER instructions
1610     case 184: case 216: case 217: case 248:
1611     case 264: case 277: case 331: case 360:
1612     case 363: case 488: case 531: case 537:
1613     case 541: case 664: case 665: case 696:
1614     case 728: case 729: case 760: case 920:
1615     case 921: case 952:
1616     goto power_inst;
1617     }
1618     }
1619    
1620     // In GUI mode, show error alert
1621     if (!PrefsFindBool("nogui")) {
1622     sprintf(str, GetString(STR_UNKNOWN_SEGV_ERR), r->nip, r->gpr[24], r->gpr[1], opcode);
1623     ErrorAlert(str);
1624     QuitEmulator();
1625     return;
1626     }
1627     }
1628    
1629     // For all other errors, jump into debugger (sort of...)
1630     if (!ready_for_signals) {
1631     printf("SIGILL\n");
1632     printf(" sigcontext %p, pt_regs %p\n", sc, r);
1633     printf(
1634     " pc %08lx lr %08lx ctr %08lx msr %08lx\n"
1635     " xer %08lx cr %08lx \n"
1636     " r0 %08lx r1 %08lx r2 %08lx r3 %08lx\n"
1637     " r4 %08lx r5 %08lx r6 %08lx r7 %08lx\n"
1638     " r8 %08lx r9 %08lx r10 %08lx r11 %08lx\n"
1639     " r12 %08lx r13 %08lx r14 %08lx r15 %08lx\n"
1640     " r16 %08lx r17 %08lx r18 %08lx r19 %08lx\n"
1641     " r20 %08lx r21 %08lx r22 %08lx r23 %08lx\n"
1642     " r24 %08lx r25 %08lx r26 %08lx r27 %08lx\n"
1643     " r28 %08lx r29 %08lx r30 %08lx r31 %08lx\n",
1644     r->nip, r->link, r->ctr, r->msr,
1645     r->xer, r->ccr,
1646     r->gpr[0], r->gpr[1], r->gpr[2], r->gpr[3],
1647     r->gpr[4], r->gpr[5], r->gpr[6], r->gpr[7],
1648     r->gpr[8], r->gpr[9], r->gpr[10], r->gpr[11],
1649     r->gpr[12], r->gpr[13], r->gpr[14], r->gpr[15],
1650     r->gpr[16], r->gpr[17], r->gpr[18], r->gpr[19],
1651     r->gpr[20], r->gpr[21], r->gpr[22], r->gpr[23],
1652     r->gpr[24], r->gpr[25], r->gpr[26], r->gpr[27],
1653     r->gpr[28], r->gpr[29], r->gpr[30], r->gpr[31]);
1654     exit(1);
1655     QuitEmulator();
1656     return;
1657     } else {
1658     // We crashed. Save registers, tell tick thread and loop forever
1659     sigsegv_regs = *(sigregs *)r;
1660     emul_thread_fatal = true;
1661     for (;;) ;
1662     }
1663     rti:;
1664     }
1665     #endif
1666    
1667    
1668     /*
1669     * Display alert
1670     */
1671    
1672     #ifdef ENABLE_GTK
1673     static void dl_destroyed(void)
1674     {
1675     gtk_main_quit();
1676     }
1677    
1678     static void dl_quit(GtkWidget *dialog)
1679     {
1680     gtk_widget_destroy(dialog);
1681     }
1682    
1683     void display_alert(int title_id, int prefix_id, int button_id, const char *text)
1684     {
1685     char str[256];
1686     sprintf(str, GetString(prefix_id), text);
1687    
1688     GtkWidget *dialog = gtk_dialog_new();
1689     gtk_window_set_title(GTK_WINDOW(dialog), GetString(title_id));
1690     gtk_container_border_width(GTK_CONTAINER(dialog), 5);
1691     gtk_widget_set_uposition(GTK_WIDGET(dialog), 100, 150);
1692     gtk_signal_connect(GTK_OBJECT(dialog), "destroy", GTK_SIGNAL_FUNC(dl_destroyed), NULL);
1693    
1694     GtkWidget *label = gtk_label_new(str);
1695     gtk_widget_show(label);
1696     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, TRUE, TRUE, 0);
1697    
1698     GtkWidget *button = gtk_button_new_with_label(GetString(button_id));
1699     gtk_widget_show(button);
1700     gtk_signal_connect_object(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(dl_quit), GTK_OBJECT(dialog));
1701     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area), button, FALSE, FALSE, 0);
1702     GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1703     gtk_widget_grab_default(button);
1704     gtk_widget_show(dialog);
1705    
1706     gtk_main();
1707     }
1708     #endif
1709    
1710    
1711     /*
1712     * Display error alert
1713     */
1714    
1715     void ErrorAlert(const char *text)
1716     {
1717     #ifdef ENABLE_GTK
1718     if (PrefsFindBool("nogui") || x_display == NULL) {
1719     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1720     return;
1721     }
1722     VideoQuitFullScreen();
1723     display_alert(STR_ERROR_ALERT_TITLE, STR_GUI_ERROR_PREFIX, STR_QUIT_BUTTON, text);
1724     #else
1725     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1726     #endif
1727     }
1728    
1729    
1730     /*
1731     * Display warning alert
1732     */
1733    
1734     void WarningAlert(const char *text)
1735     {
1736     #ifdef ENABLE_GTK
1737     if (PrefsFindBool("nogui") || x_display == NULL) {
1738     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1739     return;
1740     }
1741     display_alert(STR_WARNING_ALERT_TITLE, STR_GUI_WARNING_PREFIX, STR_OK_BUTTON, text);
1742     #else
1743     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1744     #endif
1745     }
1746    
1747    
1748     /*
1749     * Display choice alert
1750     */
1751    
1752     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1753     {
1754     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1755     return false; //!!
1756     }