ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.96
Committed: 2011-12-28T23:30:25Z (12 years, 10 months ago) by asvitkine
Branch: MAIN
Changes since 1.95: +58 -51 lines
Log Message:
refactor install_signal_handlers() into its own function

File Contents

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