ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.77
Committed: 2006-10-26T05:25:19Z (17 years, 7 months ago) by gbeauche
Branch: MAIN
Changes since 1.76: +9 -3 lines
Log Message:
Update CPU table to kernel 2.6.17+ code (POWER6, Cell, PA6T). Fix detection
of the CPU string (separator is actually ','). Fix detection of CPU clock
frequency when it is expressed as a float.

File Contents

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