ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.95
Committed: 2011-12-28T23:24:30Z (12 years, 5 months ago) by asvitkine
Branch: MAIN
Changes since 1.94: +36 -31 lines
Log Message:
refactor load_mac_rom() into a function

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