ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.58
Committed: 2005-01-30T21:48:20Z (19 years, 9 months ago) by gbeauche
Branch: MAIN
Changes since 1.57: +1 -1 lines
Log Message:
Happy New Year 2005!

File Contents

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