ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.84
Committed: 2009-07-23T19:12:50Z (14 years, 10 months ago) by asvitkine
Branch: MAIN
Changes since 1.83: +26 -2 lines
Log Message:
support for .sheepvm bundles on macosx, containing "prefs" and "nvram" files

File Contents

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