ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.103
Committed: 2012-03-01T04:25:10Z (12 years, 8 months ago) by asvitkine
Branch: MAIN
CVS Tags: HEAD
Changes since 1.102: +1 -4 lines
Log Message:
fix some unused vars warnings

File Contents

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