ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/main_unix.cpp
Revision: 1.30
Committed: 2001-02-02T20:52:57Z (23 years, 9 months ago) by cebix
Branch: MAIN
CVS Tags: snapshot-17022001
Changes since 1.29: +1 -1 lines
Log Message:
- bumped version number to 0.9
- updated copyright dates

File Contents

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