ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/SheepShaver/src/Unix/main_unix.cpp
Revision: 1.60
Committed: 2005-02-27T21:52:06Z (19 years, 8 months ago) by gbeauche
Branch: MAIN
Changes since 1.59: +45 -6 lines
Log Message:
Fix native Linux/ppc with recent enough glibc that supports TLS; r2 is used
in that case. Tell me if I broke other arches, e.g. r13 is no longer saved
in Video and Ethernet stubs, though it seems to be OK.

Colateral feature: SheepShaver should now run on Linux/ppc64 with relevant
32-bit runtime. Native Linux/ppc64 support is harder as low mem globals are
32-bit in mind and e.g. the TLS register there is %r13, %r2 is the TOC
(PowerOpen/AIX ABI)

File Contents

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