ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.3
Committed: 2002-04-21T15:07:08Z (22 years, 6 months ago) by gbeauche
Branch: MAIN
Changes since 1.2: +5 -81 lines
Log Message:
Add support to decode parcels-based ROMs
- include/rom_patches.h (DecodeROM): Declare.
- rom_patches.cpp (DecodeROM): Define.
- Unix/main_unix.cpp, BeOS/main_beos.cpp (decode_lzss): Move to...
- rom_patches.cpp (decode_lzss): ... here.
- Unix/main_unix.cpp (main): Call DecodeROM().
- BeOS/main_beos.cpp (SheepShaver::load_rom): Call DecodeROM().

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