ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.78
Committed: 2007-08-27T21:45:13Z (17 years, 2 months ago) by asvitkine
Branch: MAIN
Changes since 1.77: +5 -0 lines
Log Message:
use the new SDL 1.2.12 env variable to allow the OS to launch the screensaver
when sheepshaver is running - must be linking to sdl 1.2.12 or later for it
to take effect

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