ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.43
Committed: 2004-06-26T15:26:17Z (20 years, 4 months ago) by gbeauche
Branch: MAIN
Changes since 1.42: +32 -19 lines
Log Message:
Performance of VOSF is heuristically determined at run-time, so have to
initialize SIGSEGV handlers early, as in Basilisk II. Besides, also add
missing call to vm_init() in case host system doesn't have MAP_ANON.

File Contents

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