ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/main_unix.cpp
Revision: 1.17
Committed: 2000-07-24T15:17:07Z (24 years, 3 months ago) by cebix
Branch: MAIN
Changes since 1.16: +17 -5 lines
Log Message:
- Mac ROM and RAM are allocated with malloc() instead of "new" (because
  -fomit-frame-pointer breaks exceptions), and an error message is displayed
  if the allocation fails

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * main_unix.cpp - Startup code for Unix
3     *
4 cebix 1.11 * Basilisk II (C) 1997-2000 Christian Bauer
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     #include "sysdeps.h"
22    
23     #include <stdio.h>
24     #include <stdlib.h>
25     #include <signal.h>
26 cebix 1.12 #include <errno.h>
27     #include <X11/Xlib.h>
28    
29     #ifdef HAVE_PTHREADS
30     # include <pthread.h>
31     #endif
32    
33     #if defined(USE_MAPPED_MEMORY) || REAL_ADDRESSING
34     # include <sys/mman.h>
35     #endif
36    
37     #if !EMULATED_68K && defined(__NetBSD__)
38     # include <m68k/sync_icache.h>
39     # include <m68k/frame.h>
40     # include <sys/param.h>
41     # include <sys/sysctl.h>
42     struct sigstate {
43     int ss_flags;
44     struct frame ss_frame;
45     struct fpframe ss_fpstate;
46     };
47     # define SS_FPSTATE 0x02
48     # define SS_USERREGS 0x04
49     #endif
50    
51     #ifdef ENABLE_GTK
52     # include <gtk/gtk.h>
53     #endif
54    
55     #ifdef ENABLE_XF86_DGA
56     # include <X11/Xutil.h>
57     # include <X11/extensions/xf86dga.h>
58     #endif
59 cebix 1.1
60     #include "cpu_emulation.h"
61     #include "sys.h"
62 cebix 1.3 #include "rom_patches.h"
63 cebix 1.1 #include "xpram.h"
64     #include "timer.h"
65     #include "video.h"
66 cebix 1.12 #include "emul_op.h"
67 cebix 1.1 #include "prefs.h"
68     #include "prefs_editor.h"
69     #include "macos_util.h"
70     #include "user_strings.h"
71     #include "version.h"
72     #include "main.h"
73    
74 cebix 1.12 #ifdef ENABLE_MON
75     # include "mon.h"
76     #endif
77    
78 cebix 1.13 #define DEBUG 0
79 cebix 1.1 #include "debug.h"
80    
81    
82 cebix 1.12 // Constants
83     const char ROM_FILE_NAME[] = "ROM";
84     const int SIG_STACK_SIZE = SIGSTKSZ; // Size of signal stack
85     const int SCRATCH_MEM_SIZE = 0x10000; // Size of scratch memory area
86 cebix 1.1
87 cebix 1.4
88 cebix 1.12 #if !EMULATED_68K
89     // RAM and ROM pointers
90     uint32 RAMBaseMac; // RAM base (Mac address space)
91     uint8 *RAMBaseHost; // RAM base (host address space)
92     uint32 RAMSize; // Size of RAM
93     uint32 ROMBaseMac; // ROM base (Mac address space)
94     uint8 *ROMBaseHost; // ROM base (host address space)
95     uint32 ROMSize; // Size of ROM
96 cebix 1.9 #endif
97    
98 cebix 1.1
99     // CPU and FPU type, addressing mode
100     int CPUType;
101     bool CPUIs68060;
102     int FPUType;
103     bool TwentyFourBitAddressing;
104    
105    
106     // Global variables
107 cebix 1.13 char *x_display_name = NULL; // X11 display name
108 cebix 1.1 Display *x_display = NULL; // X11 display handle
109    
110 cebix 1.12 static int zero_fd = -1; // FD of /dev/zero
111     static uint8 last_xpram[256]; // Buffer for monitoring XPRAM changes
112    
113     #ifdef HAVE_PTHREADS
114     static pthread_t emul_thread; // Handle of MacOS emulation thread (main thread)
115    
116 cebix 1.1 static bool xpram_thread_active = false; // Flag: XPRAM watchdog installed
117     static volatile bool xpram_thread_cancel = false; // Flag: Cancel XPRAM thread
118     static pthread_t xpram_thread; // XPRAM watchdog
119    
120     static bool tick_thread_active = false; // Flag: 60Hz thread installed
121     static volatile bool tick_thread_cancel = false; // Flag: Cancel 60Hz thread
122     static pthread_t tick_thread; // 60Hz thread
123     static pthread_attr_t tick_thread_attr; // 60Hz thread attributes
124    
125 cebix 1.12 #if EMULATED_68K
126 cebix 1.1 static pthread_mutex_t intflag_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect InterruptFlags
127 cebix 1.12 #endif
128     #endif
129    
130     #if !EMULATED_68K
131     #define SIG_IRQ SIGUSR1
132     static struct sigaction sigirq_sa; // Virtual 68k interrupt signal
133     static struct sigaction sigill_sa; // Illegal instruction
134     static void *sig_stack = NULL; // Stack for signal handlers
135     uint16 EmulatedSR; // Emulated bits of SR (supervisor bit and interrupt mask)
136     uint32 ScratchMem = NULL; // Scratch memory for Mac ROM writes
137     #endif
138    
139     static struct sigaction timer_sa; // sigaction used for timer
140 cebix 1.1
141     #if defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
142     #define SIG_TIMER SIGRTMIN
143 cebix 1.12 static timer_t timer; // 60Hz timer
144 cebix 1.1 #endif
145    
146 cebix 1.12 #ifdef ENABLE_MON
147     static struct sigaction sigint_sa; // sigaction for SIGINT handler
148 cebix 1.4 static void sigint_handler(...);
149 cebix 1.15 #endif
150    
151     #if REAL_ADDRESSING
152     static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
153 cebix 1.4 #endif
154    
155 cebix 1.12 #ifdef USE_MAPPED_MEMORY
156     extern char *address_space, *good_address_map;
157     #endif
158    
159 cebix 1.1
160     // Prototypes
161     static void *xpram_func(void *arg);
162     static void *tick_func(void *arg);
163     static void one_tick(...);
164 cebix 1.12 #if !EMULATED_68K
165     static void sigirq_handler(int sig, int code, struct sigcontext *scp);
166     static void sigill_handler(int sig, int code, struct sigcontext *scp);
167     extern "C" void EmulOpTrampoline(void);
168     #endif
169 cebix 1.1
170    
171     /*
172     * Ersatz functions
173     */
174    
175     extern "C" {
176    
177     #ifndef HAVE_STRDUP
178     char *strdup(const char *s)
179     {
180     char *n = (char *)malloc(strlen(s) + 1);
181     strcpy(n, s);
182     return n;
183     }
184     #endif
185    
186     }
187    
188    
189     /*
190     * Main program
191     */
192    
193     int main(int argc, char **argv)
194     {
195 cebix 1.12 char str[256];
196    
197 cebix 1.1 // Initialize variables
198     RAMBaseHost = NULL;
199     ROMBaseHost = NULL;
200     srand(time(NULL));
201     tzset();
202    
203     // Print some info
204     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
205     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
206    
207     // Parse arguments
208     for (int i=1; i<argc; i++) {
209     if (strcmp(argv[i], "-display") == 0 && ++i < argc)
210     x_display_name = argv[i];
211 cebix 1.4 else if (strcmp(argv[i], "-break") == 0 && ++i < argc)
212     ROMBreakpoint = strtol(argv[i], NULL, 0);
213 cebix 1.6 else if (strcmp(argv[i], "-rominfo") == 0)
214     PrintROMInfo = true;
215 cebix 1.1 }
216    
217     // Open display
218     x_display = XOpenDisplay(x_display_name);
219     if (x_display == NULL) {
220     char str[256];
221     sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
222     ErrorAlert(str);
223     QuitEmulator();
224     }
225    
226 cebix 1.12 #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
227 cebix 1.1 // Fork out, so we can return from fullscreen mode when things get ugly
228 cebix 1.2 XF86DGAForkApp(DefaultScreen(x_display));
229 cebix 1.1 #endif
230    
231 cebix 1.12 #ifdef ENABLE_GTK
232 cebix 1.1 // Init GTK
233     gtk_set_locale();
234     gtk_init(&argc, &argv);
235     #endif
236    
237     // Read preferences
238     PrefsInit();
239    
240     // Init system routines
241     SysInit();
242    
243     // Show preferences editor
244     if (!PrefsFindBool("nogui"))
245     if (!PrefsEditor())
246     QuitEmulator();
247    
248 cebix 1.12 // Open /dev/zero
249     zero_fd = open("/dev/zero", O_RDWR);
250     if (zero_fd < 0) {
251     sprintf(str, GetString(STR_NO_DEV_ZERO_ERR), strerror(errno));
252     ErrorAlert(str);
253     QuitEmulator();
254     }
255    
256 cebix 1.9 // Read RAM size
257 cebix 1.1 RAMSize = PrefsFindInt32("ramsize") & 0xfff00000; // Round down to 1MB boundary
258     if (RAMSize < 1024*1024) {
259     WarningAlert(GetString(STR_SMALL_RAM_WARN));
260     RAMSize = 1024*1024;
261     }
262 cebix 1.9
263 cebix 1.12 #if REAL_ADDRESSING
264     // Create Low Memory area (0x0000..0x2000)
265     if (mmap((char *)0x0000, 0x2000, PROT_READ | PROT_WRITE, MAP_FIXED | MAP_PRIVATE, zero_fd, 0) == (void *)-1) {
266     sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
267     ErrorAlert(str);
268     QuitEmulator();
269     }
270     lm_area_mapped = true;
271     #endif
272    
273     #if !EMULATED_68K
274     // Allocate scratch memory
275     ScratchMem = (uint32)malloc(SCRATCH_MEM_SIZE);
276     if (ScratchMem == NULL) {
277     ErrorAlert(GetString(STR_NO_MEM_ERR));
278     QuitEmulator();
279     }
280     ScratchMem += SCRATCH_MEM_SIZE/2; // ScratchMem points to middle of block
281     #endif
282    
283 cebix 1.9 // Create areas for Mac RAM and ROM
284 cebix 1.12 #if defined(USE_MAPPED_MEMORY)
285     good_address_map = (char *)mmap(NULL, 1<<24, PROT_READ, MAP_PRIVATE, zero_fd, 0);
286     address_space = (char *)mmap(NULL, 1<<24, PROT_READ | PROT_WRITE, MAP_PRIVATE, zero_fd, 0);
287 cebix 1.9 if ((int)address_space < 0 || (int)good_address_map < 0) {
288     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
289     QuitEmulator();
290     }
291 cebix 1.12 RAMBaseHost = (uint8 *)mmap(address_space, RAMSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, zero_fd, 0);
292     ROMBaseHost = (uint8 *)mmap(address_space + 0x00400000, 0x80000, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_FIXED, zero_fd, 0);
293 cebix 1.9 char *nam = tmpnam(NULL);
294     int good_address_fd = open(nam, O_CREAT | O_RDWR, 0600);
295     char buffer[4096];
296     memset(buffer, 1, sizeof(buffer));
297     write(good_address_fd, buffer, sizeof(buffer));
298     unlink(nam);
299     for (int i=0; i<RAMSize; i+=4096)
300     mmap(good_address_map + i, 4096, PROT_READ, MAP_FIXED | MAP_PRIVATE, good_address_fd, 0);
301     for (int i=0; i<0x80000; i+=4096)
302     mmap(good_address_map + i + 0x00400000, 4096, PROT_READ, MAP_FIXED | MAP_PRIVATE, good_address_fd, 0);
303     #else
304 cebix 1.17 RAMBaseHost = (uint8 *)malloc(RAMSize);
305     ROMBaseHost = (uint8 *)malloc(0x100000);
306 cebix 1.9 #endif
307 cebix 1.17 if (RAMBaseHost == NULL || ROMBaseHost == NULL) {
308     ErrorAlert(GetString(STR_NO_MEM_ERR));
309     QuitEmulator();
310     }
311 cebix 1.12 #if REAL_ADDRESSING && !EMULATED_68K
312     RAMBaseMac = (uint32)RAMBaseHost;
313     ROMBaseMac = (uint32)ROMBaseHost;
314     #endif
315     D(bug("Mac RAM starts at %p (%08x)\n", RAMBaseHost, RAMBaseMac));
316     D(bug("Mac ROM starts at %p (%08x)\n", ROMBaseHost, ROMBaseMac));
317 cebix 1.1
318     // Get rom file path from preferences
319     const char *rom_path = PrefsFindString("rom");
320    
321     // Load Mac ROM
322     int rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
323     if (rom_fd < 0) {
324     ErrorAlert(GetString(STR_NO_ROM_FILE_ERR));
325     QuitEmulator();
326     }
327     printf(GetString(STR_READING_ROM_FILE));
328     ROMSize = lseek(rom_fd, 0, SEEK_END);
329     if (ROMSize != 64*1024 && ROMSize != 128*1024 && ROMSize != 256*1024 && ROMSize != 512*1024 && ROMSize != 1024*1024) {
330     ErrorAlert(GetString(STR_ROM_SIZE_ERR));
331     close(rom_fd);
332     QuitEmulator();
333     }
334     lseek(rom_fd, 0, SEEK_SET);
335     if (read(rom_fd, ROMBaseHost, ROMSize) != (ssize_t)ROMSize) {
336     ErrorAlert(GetString(STR_ROM_FILE_READ_ERR));
337     close(rom_fd);
338     QuitEmulator();
339     }
340    
341 cebix 1.12 #if !EMULATED_68K
342     // Get CPU model
343     int mib[2] = {CTL_HW, HW_MODEL};
344     char *model;
345     size_t model_len;
346     sysctl(mib, 2, NULL, &model_len, NULL, 0);
347     model = (char *)malloc(model_len);
348     sysctl(mib, 2, model, &model_len, NULL, 0);
349     D(bug("Model: %s\n", model));
350    
351     // Set CPU and FPU type
352     CPUIs68060 = false;
353     if (strstr(model, "020"))
354     CPUType = 2;
355     else if (strstr(model, "030"))
356     CPUType = 3;
357     else if (strstr(model, "040"))
358     CPUType = 4;
359     else if (strstr(model, "060")) {
360     CPUType = 4;
361     CPUIs68060 = true;
362     } else {
363     printf("WARNING: Cannot detect CPU type, assuming 68020\n");
364     CPUType = 2;
365     }
366     FPUType = 0; //!!
367     TwentyFourBitAddressing = false;
368     #endif
369    
370 cebix 1.3 // Initialize everything
371     if (!InitAll())
372 cebix 1.1 QuitEmulator();
373 cebix 1.12 D(bug("Initialization complete\n"));
374    
375     #ifdef HAVE_PTHREADS
376     // Get handle of main thread
377     emul_thread = pthread_self();
378     #endif
379    
380     #if !EMULATED_68K
381     // (Virtual) supervisor mode, disable interrupts
382     EmulatedSR = 0x2700;
383    
384     // Create and install stack for signal handlers
385     sig_stack = malloc(SIG_STACK_SIZE);
386     D(bug("Signal stack at %p\n", sig_stack));
387     if (sig_stack == NULL) {
388     ErrorAlert(GetString(STR_NOT_ENOUGH_MEMORY_ERR));
389     QuitEmulator();
390     }
391     stack_t new_stack;
392     new_stack.ss_sp = sig_stack;
393     new_stack.ss_flags = 0;
394     new_stack.ss_size = SIG_STACK_SIZE;
395     if (sigaltstack(&new_stack, NULL) < 0) {
396     sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
397     ErrorAlert(str);
398     QuitEmulator();
399     }
400    
401     // Install SIGILL handler for emulating privileged instructions and
402     // executing A-Trap and EMUL_OP opcodes
403     sigemptyset(&sigill_sa.sa_mask); // Block virtual 68k interrupts during SIGILL handling
404     sigaddset(&sigill_sa.sa_mask, SIG_IRQ);
405     sigaddset(&sigill_sa.sa_mask, SIGALRM);
406     sigill_sa.sa_handler = (void (*)(int))sigill_handler;
407     sigill_sa.sa_flags = SA_ONSTACK;
408     if (sigaction(SIGILL, &sigill_sa, NULL) < 0) {
409     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGILL", strerror(errno));
410     ErrorAlert(str);
411     QuitEmulator();
412     }
413    
414     // Install virtual 68k interrupt signal handler
415     sigemptyset(&sigirq_sa.sa_mask);
416     sigaddset(&sigirq_sa.sa_mask, SIGALRM);
417     sigirq_sa.sa_handler = (void (*)(int))sigirq_handler;
418     sigirq_sa.sa_flags = SA_ONSTACK | SA_RESTART;
419     if (sigaction(SIG_IRQ, &sigirq_sa, NULL) < 0) {
420     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_IRQ", strerror(errno));
421     ErrorAlert(str);
422     QuitEmulator();
423     }
424     #endif
425 cebix 1.1
426 cebix 1.12 #ifdef ENABLE_MON
427     // Setup SIGINT handler to enter mon
428     sigemptyset(&sigint_sa.sa_mask);
429     sigint_sa.sa_handler = sigint_handler;
430     sigint_sa.sa_flags = 0;
431     sigaction(SIGINT, &sigint_sa, NULL);
432     #endif
433 cebix 1.1
434     #if defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
435 cebix 1.12
436     // POSIX.4 timers and real-time signals available, start 60Hz timer
437 cebix 1.1 sigemptyset(&timer_sa.sa_mask);
438 cebix 1.12 timer_sa.sa_sigaction = one_tick;
439 cebix 1.1 timer_sa.sa_flags = SA_SIGINFO | SA_RESTART;
440     if (sigaction(SIG_TIMER, &timer_sa, NULL) < 0) {
441 cebix 1.12 sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_TIMER", strerror(errno));
442     ErrorAlert(str);
443 cebix 1.1 QuitEmulator();
444     }
445     struct sigevent timer_event;
446     timer_event.sigev_notify = SIGEV_SIGNAL;
447     timer_event.sigev_signo = SIG_TIMER;
448     if (timer_create(CLOCK_REALTIME, &timer_event, &timer) < 0) {
449 cebix 1.12 sprintf(str, GetString(STR_TIMER_CREATE_ERR), strerror(errno));
450     ErrorAlert(str);
451 cebix 1.1 QuitEmulator();
452     }
453     struct itimerspec req;
454     req.it_value.tv_sec = 0;
455     req.it_value.tv_nsec = 16625000;
456     req.it_interval.tv_sec = 0;
457     req.it_interval.tv_nsec = 16625000;
458 cebix 1.10 if (timer_settime(timer, 0, &req, NULL) < 0) {
459 cebix 1.12 sprintf(str, GetString(STR_TIMER_SETTIME_ERR), strerror(errno));
460     ErrorAlert(str);
461 cebix 1.1 QuitEmulator();
462     }
463 cebix 1.12 D(bug("60Hz timer started\n"));
464 cebix 1.1
465 cebix 1.12 #elif defined(HAVE_PTHREADS)
466 cebix 1.1
467 cebix 1.12 // POSIX threads available, start 60Hz thread
468 cebix 1.1 pthread_attr_init(&tick_thread_attr);
469     #if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
470     if (geteuid() == 0) {
471     pthread_attr_setinheritsched(&tick_thread_attr, PTHREAD_EXPLICIT_SCHED);
472     pthread_attr_setschedpolicy(&tick_thread_attr, SCHED_FIFO);
473     struct sched_param fifo_param;
474     fifo_param.sched_priority = (sched_get_priority_min(SCHED_FIFO) + sched_get_priority_max(SCHED_FIFO)) / 2;
475     pthread_attr_setschedparam(&tick_thread_attr, &fifo_param);
476     }
477     #endif
478     tick_thread_active = (pthread_create(&tick_thread, &tick_thread_attr, tick_func, NULL) == 0);
479     if (!tick_thread_active) {
480 cebix 1.12 sprintf(str, GetString(STR_TICK_THREAD_ERR), strerror(errno));
481     ErrorAlert(str);
482     QuitEmulator();
483     }
484     D(bug("60Hz thread started\n"));
485    
486     #else
487    
488     // Start 60Hz timer
489     sigemptyset(&timer_sa.sa_mask); // Block virtual 68k interrupts during SIGARLM handling
490     sigaddset(&timer_sa.sa_mask, SIG_IRQ);
491     timer_sa.sa_handler = one_tick;
492     timer_sa.sa_flags = SA_ONSTACK | SA_RESTART;
493     if (sigaction(SIGALRM, &timer_sa, NULL) < 0) {
494     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGALRM", strerror(errno));
495     ErrorAlert(str);
496 cebix 1.1 QuitEmulator();
497     }
498 cebix 1.12 struct itimerval req;
499     req.it_interval.tv_sec = req.it_value.tv_sec = 0;
500     req.it_interval.tv_usec = req.it_value.tv_usec = 16625;
501     setitimer(ITIMER_REAL, &req, NULL);
502    
503 cebix 1.1 #endif
504    
505 cebix 1.12 #ifdef HAVE_PTHREADS
506     // Start XPRAM watchdog thread
507     memcpy(last_xpram, XPRAM, 256);
508     xpram_thread_active = (pthread_create(&xpram_thread, NULL, xpram_func, NULL) == 0);
509     D(bug("XPRAM thread started\n"));
510 cebix 1.4 #endif
511    
512 cebix 1.1 // Start 68k and jump to ROM boot routine
513 cebix 1.12 D(bug("Starting emulation...\n"));
514 cebix 1.1 Start680x0();
515    
516     QuitEmulator();
517     return 0;
518     }
519    
520    
521     /*
522     * Quit emulator
523     */
524    
525     void QuitEmulator(void)
526     {
527 cebix 1.12 D(bug("QuitEmulator\n"));
528    
529     #if EMULATED_68K
530 cebix 1.1 // Exit 680x0 emulation
531     Exit680x0();
532 cebix 1.12 #endif
533 cebix 1.1
534     #if defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
535     // Stop 60Hz timer
536     timer_delete(timer);
537 cebix 1.12 #elif defined(HAVE_PTHREADS)
538 cebix 1.1 // Stop 60Hz thread
539     if (tick_thread_active) {
540     tick_thread_cancel = true;
541     #ifdef HAVE_PTHREAD_CANCEL
542     pthread_cancel(tick_thread);
543     #endif
544     pthread_join(tick_thread, NULL);
545     }
546 cebix 1.12 #else
547     struct itimerval req;
548     req.it_interval.tv_sec = req.it_value.tv_sec = 0;
549     req.it_interval.tv_usec = req.it_value.tv_usec = 0;
550     setitimer(ITIMER_REAL, &req, NULL);
551 cebix 1.1 #endif
552    
553 cebix 1.12 #ifdef HAVE_PTHREADS
554 cebix 1.1 // Stop XPRAM watchdog thread
555     if (xpram_thread_active) {
556     xpram_thread_cancel = true;
557     #ifdef HAVE_PTHREAD_CANCEL
558     pthread_cancel(xpram_thread);
559     #endif
560     pthread_join(xpram_thread, NULL);
561     }
562 cebix 1.12 #endif
563 cebix 1.1
564 cebix 1.3 // Deinitialize everything
565     ExitAll();
566 cebix 1.1
567     // Delete ROM area
568 cebix 1.17 if (ROMBaseHost) {
569     free(ROMBaseHost);
570     ROMBaseHost = NULL;
571     }
572 cebix 1.1
573     // Delete RAM area
574 cebix 1.17 if (RAMBaseHost) {
575     free(RAMBaseHost);
576     RAMBaseHost = NULL;
577     }
578 cebix 1.1
579 cebix 1.12 #if !EMULATED_68K
580     // Delete scratch memory area
581 cebix 1.17 if (ScratchMem) {
582 cebix 1.12 free((void *)(ScratchMem - SCRATCH_MEM_SIZE/2));
583 cebix 1.17 ScratchMem = NULL;
584     }
585 cebix 1.12 #endif
586    
587     #if REAL_ADDRESSING
588     // Delete Low Memory area
589     if (lm_area_mapped)
590     munmap((char *)0x0000, 0x2000);
591     #endif
592    
593     // Close /dev/zero
594     if (zero_fd > 0)
595     close(zero_fd);
596    
597 cebix 1.1 // Exit system routines
598     SysExit();
599    
600     // Exit preferences
601     PrefsExit();
602    
603     // Close X11 server connection
604     if (x_display)
605     XCloseDisplay(x_display);
606    
607     exit(0);
608     }
609    
610    
611     /*
612     * Code was patched, flush caches if neccessary (i.e. when using a real 680x0
613     * or a dynamically recompiling emulator)
614     */
615    
616     void FlushCodeCache(void *start, uint32 size)
617     {
618 cebix 1.12 #if !EMULATED_68K && defined(__NetBSD__)
619     m68k_sync_icache(start, size);
620     #endif
621 cebix 1.4 }
622    
623    
624     /*
625     * SIGINT handler, enters mon
626     */
627    
628 cebix 1.12 #ifdef ENABLE_MON
629 cebix 1.4 static void sigint_handler(...)
630     {
631 cebix 1.12 #if EMULATED_68K
632 cebix 1.8 uaecptr nextpc;
633 cebix 1.12 extern void m68k_dumpstate(uaecptr *nextpc);
634 cebix 1.8 m68k_dumpstate(&nextpc);
635 cebix 1.12 #else
636 cebix 1.4 char *arg[2] = {"rmon", NULL};
637     mon(1, arg);
638     QuitEmulator();
639 cebix 1.12 #endif
640 cebix 1.1 }
641     #endif
642    
643    
644     /*
645     * Interrupt flags (must be handled atomically!)
646     */
647    
648     uint32 InterruptFlags = 0;
649    
650 cebix 1.12 #if EMULATED_68K
651 cebix 1.1 void SetInterruptFlag(uint32 flag)
652     {
653 cebix 1.12 #ifdef HAVE_PTHREADS
654 cebix 1.1 pthread_mutex_lock(&intflag_lock);
655     InterruptFlags |= flag;
656     pthread_mutex_unlock(&intflag_lock);
657 cebix 1.12 #else
658     InterruptFlags |= flag; // Pray that this is an atomic operation...
659     #endif
660 cebix 1.1 }
661    
662     void ClearInterruptFlag(uint32 flag)
663     {
664 cebix 1.12 #ifdef HAVE_PTHREADS
665 cebix 1.1 pthread_mutex_lock(&intflag_lock);
666     InterruptFlags &= ~flag;
667     pthread_mutex_unlock(&intflag_lock);
668 cebix 1.12 #else
669     InterruptFlags &= ~flag;
670     #endif
671     }
672     #endif
673    
674     #if !EMULATED_68K
675     void TriggerInterrupt(void)
676     {
677     #if defined(HAVE_PTHREADS)
678     pthread_kill(emul_thread, SIG_IRQ);
679     #else
680     raise(SIG_IRQ);
681     #endif
682     }
683     #endif
684    
685    
686     /*
687     * XPRAM watchdog thread (saves XPRAM every minute)
688     */
689    
690     static void xpram_watchdog(void)
691     {
692     if (memcmp(last_xpram, XPRAM, 256)) {
693     memcpy(last_xpram, XPRAM, 256);
694     SaveXPRAM();
695     }
696     }
697    
698     #ifdef HAVE_PTHREADS
699     static void *xpram_func(void *arg)
700     {
701     while (!xpram_thread_cancel) {
702 cebix 1.16 for (int i=0; i<60 && !xpram_thread_cancel; i++)
703     Delay_usec(1000000);
704 cebix 1.12 xpram_watchdog();
705     }
706     return NULL;
707 cebix 1.1 }
708 cebix 1.12 #endif
709 cebix 1.1
710    
711     /*
712     * 60Hz thread (really 60.15Hz)
713     */
714    
715 cebix 1.12 static void one_second(void)
716     {
717     // Pseudo Mac 1Hz interrupt, update local time
718     WriteMacInt32(0x20c, TimerDateTime());
719    
720 cebix 1.14 SetInterruptFlag(INTFLAG_60HZ);
721     TriggerInterrupt();
722    
723 cebix 1.12 #ifndef HAVE_PTHREADS
724     static int second_counter = 0;
725     if (++second_counter > 60) {
726     second_counter = 0;
727     xpram_watchdog();
728     }
729     #endif
730     }
731    
732 cebix 1.1 static void one_tick(...)
733     {
734     static int tick_counter = 0;
735     if (++tick_counter > 60) {
736     tick_counter = 0;
737 cebix 1.12 one_second();
738 cebix 1.1 }
739    
740 cebix 1.12 #ifndef HAVE_PTHREADS
741     // No threads available, perform video refresh from here
742     VideoRefresh();
743     #endif
744    
745 cebix 1.1 // Trigger 60Hz interrupt
746     if (ROMVersion != ROM_VERSION_CLASSIC || HasMacStarted()) {
747     SetInterruptFlag(INTFLAG_60HZ);
748     TriggerInterrupt();
749     }
750     }
751    
752 cebix 1.12 #ifdef HAVE_PTHREADS
753 cebix 1.1 static void *tick_func(void *arg)
754     {
755 cebix 1.16 uint64 next = GetTicks_usec();
756 cebix 1.1 while (!tick_thread_cancel) {
757 cebix 1.16 one_tick();
758     next += 16625;
759     int64 delay = next - GetTicks_usec();
760     if (delay > 0)
761     Delay_usec(delay);
762     else if (delay < -16625)
763     next = GetTicks_usec();
764     }
765     return NULL;
766     }
767     #endif
768 cebix 1.1
769 cebix 1.16
770     /*
771     * Get current value of microsecond timer
772     */
773    
774     uint64 GetTicks_usec(void)
775     {
776     #ifdef HAVE_CLOCK_GETTIME
777     struct timespec t;
778     clock_gettime(CLOCK_REALTIME, &t);
779     return (uint64)t.tv_sec * 1000000 + t.tv_nsec / 1000;
780 cebix 1.1 #else
781 cebix 1.16 struct timeval t;
782     gettimeofday(&t, NULL);
783     return (uint64)t.tv_sec * 1000000 + t.tv_usec;
784 cebix 1.1 #endif
785 cebix 1.16 }
786 cebix 1.1
787 cebix 1.16
788     /*
789     * Delay by specified number of microseconds (<1 second)
790     * (adapted from SDL_Delay() source)
791     */
792    
793     void Delay_usec(uint32 usec)
794     {
795     int was_error;
796     #ifndef __linux__ // Non-Linux implementations need to calculate time left
797     uint64 then, now, elapsed;
798     #endif
799     struct timeval tv;
800    
801     // Set the timeout interval - Linux only needs to do this once
802     #ifdef __linux__
803     tv.tv_sec = 0;
804     tv.tv_usec = usec;
805     #else
806     then = GetTicks_usec();
807     #endif
808     do {
809     errno = 0;
810     #ifndef __linux__
811     /* Calculate the time interval left (in case of interrupt) */
812     now = GetTicks_usec();
813     elapsed = now - then;
814     then = now;
815     if (elapsed >= usec)
816     break;
817     usec -= elapsed;
818     tv.tv_sec = 0;
819     tv.tv_usec = usec;
820     #endif
821     was_error = select(0, NULL, NULL, NULL, &tv);
822     } while (was_error && (errno == EINTR));
823 cebix 1.1 }
824 cebix 1.12
825    
826     #if !EMULATED_68K
827     /*
828     * Virtual 68k interrupt handler
829     */
830    
831     static void sigirq_handler(int sig, int code, struct sigcontext *scp)
832     {
833     // Interrupts disabled? Then do nothing
834     if (EmulatedSR & 0x0700)
835     return;
836    
837     struct sigstate *state = (struct sigstate *)scp->sc_ap;
838     M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
839    
840     // Set up interrupt frame on stack
841     uint32 a7 = regs->a[7];
842     a7 -= 2;
843     WriteMacInt16(a7, 0x64);
844     a7 -= 4;
845     WriteMacInt32(a7, scp->sc_pc);
846     a7 -= 2;
847     WriteMacInt16(a7, scp->sc_ps | EmulatedSR);
848     scp->sc_sp = regs->a[7] = a7;
849    
850     // Set interrupt level
851     EmulatedSR |= 0x2100;
852    
853     // Jump to MacOS interrupt handler on return
854     scp->sc_pc = ReadMacInt32(0x64);
855     }
856 cebix 1.1
857    
858     /*
859 cebix 1.12 * SIGILL handler, for emulation of privileged instructions and executing
860     * A-Trap and EMUL_OP opcodes
861 cebix 1.1 */
862    
863 cebix 1.12 static void sigill_handler(int sig, int code, struct sigcontext *scp)
864 cebix 1.1 {
865 cebix 1.12 struct sigstate *state = (struct sigstate *)scp->sc_ap;
866     uint16 *pc = (uint16 *)scp->sc_pc;
867     uint16 opcode = *pc;
868     M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
869    
870     #define INC_PC(n) scp->sc_pc += (n)
871    
872     #define GET_SR (scp->sc_ps | EmulatedSR)
873    
874     #define STORE_SR(v) \
875     scp->sc_ps = (v) & 0xff; \
876     EmulatedSR = (v) & 0x2700; \
877     if (((v) & 0x0700) == 0 && InterruptFlags) \
878     TriggerInterrupt();
879    
880     //printf("opcode %04x at %p, sr %04x, emul_sr %04x\n", opcode, pc, scp->sc_ps, EmulatedSR);
881    
882     if ((opcode & 0xf000) == 0xa000) {
883    
884     // A-Line instruction, set up A-Line trap frame on stack
885     uint32 a7 = regs->a[7];
886     a7 -= 2;
887     WriteMacInt16(a7, 0x28);
888     a7 -= 4;
889     WriteMacInt32(a7, (uint32)pc);
890     a7 -= 2;
891     WriteMacInt16(a7, GET_SR);
892     scp->sc_sp = regs->a[7] = a7;
893    
894     // Jump to MacOS A-Line handler on return
895     scp->sc_pc = ReadMacInt32(0x28);
896    
897     } else if ((opcode & 0xff00) == 0x7100) {
898    
899     // Extended opcode, push registers on user stack
900     uint32 a7 = regs->a[7];
901     a7 -= 4;
902     WriteMacInt32(a7, (uint32)pc);
903     a7 -= 2;
904     WriteMacInt16(a7, scp->sc_ps);
905     for (int i=7; i>=0; i--) {
906     a7 -= 4;
907     WriteMacInt32(a7, regs->a[i]);
908     }
909     for (int i=7; i>=0; i--) {
910     a7 -= 4;
911     WriteMacInt32(a7, regs->d[i]);
912     }
913     scp->sc_sp = regs->a[7] = a7;
914    
915     // Jump to EmulOp trampoline code on return
916     scp->sc_pc = (uint32)EmulOpTrampoline;
917    
918     } else switch (opcode) { // Emulate privileged instructions
919    
920     case 0x40e7: // move sr,-(sp)
921     regs->a[7] -= 2;
922     WriteMacInt16(regs->a[7], GET_SR);
923     scp->sc_sp = regs->a[7];
924     INC_PC(2);
925     break;
926    
927     case 0x46df: { // move (sp)+,sr
928     uint16 sr = ReadMacInt16(regs->a[7]);
929     STORE_SR(sr);
930     regs->a[7] += 2;
931     scp->sc_sp = regs->a[7];
932     INC_PC(2);
933     break;
934     }
935    
936     case 0x007c: { // ori #xxxx,sr
937     uint16 sr = GET_SR | pc[1];
938     scp->sc_ps = sr & 0xff; // oring bits into the sr can't enable interrupts, so we don't need to call STORE_SR
939     EmulatedSR = sr & 0x2700;
940     INC_PC(4);
941     break;
942     }
943    
944     case 0x027c: { // andi #xxxx,sr
945     uint16 sr = GET_SR & pc[1];
946     STORE_SR(sr);
947     INC_PC(4);
948     break;
949     }
950    
951     case 0x46fc: // move #xxxx,sr
952     STORE_SR(pc[1]);
953     INC_PC(4);
954     break;
955    
956     case 0x46ef: { // move (xxxx,sp),sr
957     uint16 sr = ReadMacInt16(regs->a[7] + (int32)(int16)pc[1]);
958     STORE_SR(sr);
959     INC_PC(4);
960     break;
961     }
962    
963     case 0x46d8: // move (a0)+,sr
964     case 0x46d9: { // move (a1)+,sr
965     uint16 sr = ReadMacInt16(regs->a[opcode & 7]);
966     STORE_SR(sr);
967     regs->a[opcode & 7] += 2;
968     INC_PC(2);
969     break;
970     }
971 cebix 1.1
972 cebix 1.12 case 0x40f8: // move sr,xxxx.w
973     WriteMacInt16(pc[1], GET_SR);
974     INC_PC(4);
975     break;
976    
977     case 0x40d0: // move sr,(a0)
978     case 0x40d1: // move sr,(a1)
979     case 0x40d2: // move sr,(a2)
980     case 0x40d3: // move sr,(a3)
981     case 0x40d4: // move sr,(a4)
982     case 0x40d5: // move sr,(a5)
983     case 0x40d6: // move sr,(a6)
984     case 0x40d7: // move sr,(sp)
985     WriteMacInt16(regs->a[opcode & 7], GET_SR);
986     INC_PC(2);
987     break;
988    
989     case 0x40c0: // move sr,d0
990     case 0x40c1: // move sr,d1
991     case 0x40c2: // move sr,d2
992     case 0x40c3: // move sr,d3
993     case 0x40c4: // move sr,d4
994     case 0x40c5: // move sr,d5
995     case 0x40c6: // move sr,d6
996     case 0x40c7: // move sr,d7
997     regs->d[opcode & 7] = GET_SR;
998     INC_PC(2);
999     break;
1000    
1001     case 0x46c0: // move d0,sr
1002     case 0x46c1: // move d1,sr
1003     case 0x46c2: // move d2,sr
1004     case 0x46c3: // move d3,sr
1005     case 0x46c4: // move d4,sr
1006     case 0x46c5: // move d5,sr
1007     case 0x46c6: // move d6,sr
1008     case 0x46c7: { // move d7,sr
1009     uint16 sr = regs->d[opcode & 7];
1010     STORE_SR(sr);
1011     INC_PC(2);
1012     break;
1013 cebix 1.1 }
1014 cebix 1.12
1015     case 0xf327: // fsave -(sp)
1016     goto ill; //!!
1017    
1018     case 0xf35f: // frestore (sp)+
1019     goto ill; //!!
1020    
1021     case 0x4e73: { // rte (only handles format 0)
1022     uint32 a7 = regs->a[7];
1023     uint16 sr = ReadMacInt16(a7);
1024     a7 += 2;
1025     scp->sc_ps = sr & 0xff;
1026     EmulatedSR = sr & 0x2700;
1027     scp->sc_pc = ReadMacInt32(a7);
1028     a7 += 6;
1029     scp->sc_sp = regs->a[7] = a7;
1030     break;
1031 cebix 1.1 }
1032 cebix 1.12
1033     case 0x4e7a: // movec cr,x
1034     switch (pc[1]) {
1035     case 0x8801: // movec vbr,a0
1036     regs->a[0] = 0;
1037     break;
1038     case 0x9801: // movec vbr,a1
1039     regs->a[1] = 0;
1040     break;
1041     case 0x0002: // movec cacr,d0
1042     regs->d[0] = 0x3111;
1043     break;
1044     case 0x1002: // movec cacr,d1
1045     regs->d[1] = 0x3111;
1046     break;
1047     case 0x0003: // movec tc,d0
1048     regs->d[0] = 0;
1049     break;
1050     case 0x1003: // movec tc,d1
1051     regs->d[1] = 0;
1052     break;
1053     default:
1054     goto ill;
1055     }
1056     INC_PC(4);
1057     break;
1058    
1059     case 0x4e7b: // movec x,cr
1060     switch (pc[1]) {
1061     case 0x0801: // movec d0,vbr
1062     break;
1063     case 0x0002: // movec d0,cacr
1064     case 0x1002: // movec d1,cacr
1065     FlushCodeCache(NULL, 0);
1066     break;
1067     default:
1068     goto ill;
1069     }
1070     INC_PC(4);
1071     break;
1072    
1073     case 0xf478: // cpusha dc
1074     case 0xf4f8: // cpusha dc/ic
1075     FlushCodeCache(NULL, 0);
1076     INC_PC(2);
1077     break;
1078    
1079     default:
1080     ill: printf("SIGILL num %d, code %d\n", sig, code);
1081     printf(" context %p:\n", scp);
1082     printf(" onstack %08x\n", scp->sc_onstack);
1083     printf(" sp %08x\n", scp->sc_sp);
1084     printf(" fp %08x\n", scp->sc_fp);
1085     printf(" pc %08x\n", scp->sc_pc);
1086     printf(" opcode %04x\n", opcode);
1087     printf(" sr %08x\n", scp->sc_ps);
1088     printf(" state %p:\n", state);
1089     printf(" flags %d\n", state->ss_flags);
1090     for (int i=0; i<8; i++)
1091     printf(" d%d %08x\n", i, state->ss_frame.f_regs[i]);
1092     for (int i=0; i<8; i++)
1093     printf(" a%d %08x\n", i, state->ss_frame.f_regs[i+8]);
1094    
1095     #ifdef ENABLE_MON
1096     char *arg[2] = {"rmon", NULL};
1097     mon(1, arg);
1098     #endif
1099     QuitEmulator();
1100     break;
1101 cebix 1.1 }
1102     }
1103 cebix 1.12 #endif
1104 cebix 1.1
1105    
1106     /*
1107     * Display alert
1108     */
1109    
1110 cebix 1.12 #ifdef ENABLE_GTK
1111 cebix 1.1 static void dl_destroyed(void)
1112     {
1113     gtk_main_quit();
1114     }
1115    
1116     static void dl_quit(GtkWidget *dialog)
1117     {
1118     gtk_widget_destroy(dialog);
1119     }
1120    
1121     void display_alert(int title_id, int prefix_id, int button_id, const char *text)
1122     {
1123     char str[256];
1124     sprintf(str, GetString(prefix_id), text);
1125    
1126     GtkWidget *dialog = gtk_dialog_new();
1127     gtk_window_set_title(GTK_WINDOW(dialog), GetString(title_id));
1128     gtk_container_border_width(GTK_CONTAINER(dialog), 5);
1129     gtk_widget_set_uposition(GTK_WIDGET(dialog), 100, 150);
1130     gtk_signal_connect(GTK_OBJECT(dialog), "destroy", GTK_SIGNAL_FUNC(dl_destroyed), NULL);
1131    
1132     GtkWidget *label = gtk_label_new(str);
1133     gtk_widget_show(label);
1134     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, TRUE, TRUE, 0);
1135    
1136     GtkWidget *button = gtk_button_new_with_label(GetString(button_id));
1137     gtk_widget_show(button);
1138     gtk_signal_connect_object(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(dl_quit), GTK_OBJECT(dialog));
1139     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area), button, FALSE, FALSE, 0);
1140     GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1141     gtk_widget_grab_default(button);
1142     gtk_widget_show(dialog);
1143    
1144     gtk_main();
1145     }
1146     #endif
1147    
1148    
1149     /*
1150     * Display error alert
1151     */
1152    
1153     void ErrorAlert(const char *text)
1154     {
1155 cebix 1.12 #ifdef ENABLE_GTK
1156 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
1157     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1158     return;
1159     }
1160     VideoQuitFullScreen();
1161     display_alert(STR_ERROR_ALERT_TITLE, STR_GUI_ERROR_PREFIX, STR_QUIT_BUTTON, text);
1162     #else
1163     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1164     #endif
1165     }
1166    
1167    
1168     /*
1169     * Display warning alert
1170     */
1171    
1172     void WarningAlert(const char *text)
1173     {
1174 cebix 1.12 #ifdef ENABLE_GTK
1175 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
1176     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1177     return;
1178     }
1179     display_alert(STR_WARNING_ALERT_TITLE, STR_GUI_WARNING_PREFIX, STR_OK_BUTTON, text);
1180     #else
1181     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1182     #endif
1183     }
1184    
1185    
1186     /*
1187     * Display choice alert
1188     */
1189    
1190     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1191     {
1192     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1193     return false; //!!
1194     }