ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.85
Committed: 2009-08-18T02:36:59Z (14 years, 9 months ago) by asvitkine
Branch: MAIN
Changes since 1.84: +3 -1 lines
Log Message:
support both foo.sheepvm and foo.sheepvm/ command-line parameters

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