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