ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/main_unix.cpp
Revision: 1.27
Committed: 2000-11-30T16:20:52Z (23 years, 8 months ago) by cebix
Branch: MAIN
Changes since 1.26: +30 -43 lines
Log Message:
- removed USE_MAPPED_MEMORY (unused)
- fixed Delay_usec() on Solaris

File Contents

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