ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/main_unix.cpp
Revision: 1.78
Committed: 2007-12-30T08:47:34Z (16 years, 8 months ago) by gbeauche
Branch: MAIN
Changes since 1.77: +8 -5 lines
Log Message:
Sync with the new SIGSEGV API.

File Contents

# User Rev Content
1 cebix 1.1 /*
2     * main_unix.cpp - Startup code for Unix
3     *
4 gbeauche 1.65 * Basilisk II (C) 1997-2005 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 gbeauche 1.59
28     #ifdef USE_SDL
29     # include <SDL.h>
30     #endif
31    
32     #ifndef USE_SDL_VIDEO
33     # include <X11/Xlib.h>
34     #endif
35 cebix 1.12
36     #ifdef HAVE_PTHREADS
37     # include <pthread.h>
38     #endif
39    
40 cebix 1.27 #if REAL_ADDRESSING || DIRECT_ADDRESSING
41 cebix 1.12 # include <sys/mman.h>
42     #endif
43    
44     #if !EMULATED_68K && defined(__NetBSD__)
45     # include <m68k/sync_icache.h>
46     # include <m68k/frame.h>
47     # include <sys/param.h>
48     # include <sys/sysctl.h>
49     struct sigstate {
50     int ss_flags;
51     struct frame ss_frame;
52     struct fpframe ss_fpstate;
53     };
54     # define SS_FPSTATE 0x02
55     # define SS_USERREGS 0x04
56     #endif
57    
58     #ifdef ENABLE_GTK
59     # include <gtk/gtk.h>
60 cebix 1.28 # include <gdk/gdk.h>
61 cebix 1.43 # ifdef HAVE_GNOMEUI
62     # include <gnome.h>
63     # endif
64 cebix 1.12 #endif
65    
66     #ifdef ENABLE_XF86_DGA
67     # include <X11/Xutil.h>
68     # include <X11/extensions/xf86dga.h>
69     #endif
70 cebix 1.1
71 cebix 1.48 #include <string>
72     using std::string;
73    
74 cebix 1.1 #include "cpu_emulation.h"
75     #include "sys.h"
76 cebix 1.3 #include "rom_patches.h"
77 cebix 1.1 #include "xpram.h"
78     #include "timer.h"
79     #include "video.h"
80 cebix 1.12 #include "emul_op.h"
81 cebix 1.1 #include "prefs.h"
82     #include "prefs_editor.h"
83     #include "macos_util.h"
84     #include "user_strings.h"
85     #include "version.h"
86     #include "main.h"
87 gbeauche 1.33 #include "vm_alloc.h"
88 gbeauche 1.46 #include "sigsegv.h"
89 gbeauche 1.75 #include "rpc.h"
90 cebix 1.1
91 gbeauche 1.50 #if USE_JIT
92 gbeauche 1.76 extern void flush_icache_range(uint8 *start, uint32 size); // from compemu_support.cpp
93 gbeauche 1.50 #endif
94    
95 cebix 1.12 #ifdef ENABLE_MON
96     # include "mon.h"
97     #endif
98    
99 cebix 1.13 #define DEBUG 0
100 cebix 1.1 #include "debug.h"
101    
102    
103 cebix 1.12 // Constants
104     const char ROM_FILE_NAME[] = "ROM";
105 gbeauche 1.51 #if !EMULATED_68K
106 cebix 1.12 const int SIG_STACK_SIZE = SIGSTKSZ; // Size of signal stack
107 gbeauche 1.51 #endif
108 cebix 1.12 const int SCRATCH_MEM_SIZE = 0x10000; // Size of scratch memory area
109 cebix 1.1
110 cebix 1.4
111 cebix 1.12 #if !EMULATED_68K
112     // RAM and ROM pointers
113     uint32 RAMBaseMac; // RAM base (Mac address space)
114     uint8 *RAMBaseHost; // RAM base (host address space)
115     uint32 RAMSize; // Size of RAM
116     uint32 ROMBaseMac; // ROM base (Mac address space)
117     uint8 *ROMBaseHost; // ROM base (host address space)
118     uint32 ROMSize; // Size of ROM
119 cebix 1.9 #endif
120    
121 cebix 1.1
122     // CPU and FPU type, addressing mode
123     int CPUType;
124     bool CPUIs68060;
125     int FPUType;
126     bool TwentyFourBitAddressing;
127    
128    
129     // Global variables
130 gbeauche 1.59 #ifndef USE_SDL_VIDEO
131     extern char *x_display_name; // X11 display name
132     extern Display *x_display; // X11 display handle
133 gbeauche 1.64 #ifdef X11_LOCK_TYPE
134     X11_LOCK_TYPE x_display_lock = X11_LOCK_INIT; // X11 display lock
135     #endif
136 gbeauche 1.59 #endif
137 cebix 1.1
138 cebix 1.41 static uint8 last_xpram[XPRAM_SIZE]; // Buffer for monitoring XPRAM changes
139 cebix 1.12
140     #ifdef HAVE_PTHREADS
141 gbeauche 1.51 #if !EMULATED_68K
142 cebix 1.12 static pthread_t emul_thread; // Handle of MacOS emulation thread (main thread)
143 gbeauche 1.51 #endif
144 cebix 1.12
145 cebix 1.1 static bool xpram_thread_active = false; // Flag: XPRAM watchdog installed
146     static volatile bool xpram_thread_cancel = false; // Flag: Cancel XPRAM thread
147     static pthread_t xpram_thread; // XPRAM watchdog
148    
149     static bool tick_thread_active = false; // Flag: 60Hz thread installed
150     static volatile bool tick_thread_cancel = false; // Flag: Cancel 60Hz thread
151     static pthread_t tick_thread; // 60Hz thread
152     static pthread_attr_t tick_thread_attr; // 60Hz thread attributes
153    
154     static pthread_mutex_t intflag_lock = PTHREAD_MUTEX_INITIALIZER; // Mutex to protect InterruptFlags
155 cebix 1.37 #define LOCK_INTFLAGS pthread_mutex_lock(&intflag_lock)
156     #define UNLOCK_INTFLAGS pthread_mutex_unlock(&intflag_lock)
157    
158     #else
159    
160     #define LOCK_INTFLAGS
161     #define UNLOCK_INTFLAGS
162    
163 cebix 1.12 #endif
164    
165     #if !EMULATED_68K
166     #define SIG_IRQ SIGUSR1
167     static struct sigaction sigirq_sa; // Virtual 68k interrupt signal
168     static struct sigaction sigill_sa; // Illegal instruction
169     static void *sig_stack = NULL; // Stack for signal handlers
170     uint16 EmulatedSR; // Emulated bits of SR (supervisor bit and interrupt mask)
171 gbeauche 1.20 #endif
172    
173     #if USE_SCRATCHMEM_SUBTERFUGE
174 cebix 1.22 uint8 *ScratchMem = NULL; // Scratch memory for Mac ROM writes
175 cebix 1.12 #endif
176    
177 gbeauche 1.51 #if !defined(HAVE_PTHREADS)
178 cebix 1.12 static struct sigaction timer_sa; // sigaction used for timer
179 cebix 1.1
180     #if defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
181     #define SIG_TIMER SIGRTMIN
182 cebix 1.12 static timer_t timer; // 60Hz timer
183 cebix 1.1 #endif
184 gbeauche 1.51 #endif // !HAVE_PTHREADS
185 cebix 1.1
186 cebix 1.12 #ifdef ENABLE_MON
187     static struct sigaction sigint_sa; // sigaction for SIGINT handler
188 cebix 1.4 static void sigint_handler(...);
189 cebix 1.15 #endif
190    
191     #if REAL_ADDRESSING
192     static bool lm_area_mapped = false; // Flag: Low Memory area mmap()ped
193 cebix 1.22 #endif
194    
195 gbeauche 1.75 static rpc_connection_t *gui_connection = NULL; // RPC connection to the GUI
196     static const char *gui_connection_path = NULL; // GUI connection identifier
197 gbeauche 1.74
198 cebix 1.1
199     // Prototypes
200     static void *xpram_func(void *arg);
201     static void *tick_func(void *arg);
202     static void one_tick(...);
203 cebix 1.12 #if !EMULATED_68K
204     static void sigirq_handler(int sig, int code, struct sigcontext *scp);
205     static void sigill_handler(int sig, int code, struct sigcontext *scp);
206     extern "C" void EmulOpTrampoline(void);
207     #endif
208 cebix 1.1
209    
210     /*
211     * Ersatz functions
212     */
213    
214     extern "C" {
215    
216     #ifndef HAVE_STRDUP
217     char *strdup(const char *s)
218     {
219     char *n = (char *)malloc(strlen(s) + 1);
220     strcpy(n, s);
221     return n;
222     }
223     #endif
224    
225     }
226    
227    
228     /*
229 gbeauche 1.72 * Helpers to map memory that can be accessed from the Mac side
230 gbeauche 1.62 */
231    
232 gbeauche 1.77 // NOTE: VM_MAP_32BIT is only used when compiling a 64-bit JIT on specific platforms
233 gbeauche 1.62 void *vm_acquire_mac(size_t size)
234     {
235 gbeauche 1.77 return vm_acquire(size, VM_MAP_DEFAULT | VM_MAP_32BIT);
236 gbeauche 1.62 }
237    
238 gbeauche 1.71 static int vm_acquire_mac_fixed(void *addr, size_t size)
239     {
240 gbeauche 1.77 return vm_acquire_fixed(addr, size, VM_MAP_DEFAULT | VM_MAP_32BIT);
241 gbeauche 1.71 }
242    
243 gbeauche 1.62
244     /*
245 gbeauche 1.54 * SIGSEGV handler
246     */
247    
248 gbeauche 1.78 static sigsegv_return_t sigsegv_handler(sigsegv_info_t *sip)
249 gbeauche 1.54 {
250 gbeauche 1.78 const uintptr fault_address = (uintptr)sigsegv_get_fault_address(sip);
251 gbeauche 1.54 #if ENABLE_VOSF
252     // Handle screen fault
253 gbeauche 1.78 extern bool Screen_fault_handler(sigsegv_info_t *sip);
254     if (Screen_fault_handler(sip))
255 gbeauche 1.54 return SIGSEGV_RETURN_SUCCESS;
256     #endif
257    
258     #ifdef HAVE_SIGSEGV_SKIP_INSTRUCTION
259     // Ignore writes to ROM
260     if (((uintptr)fault_address - (uintptr)ROMBaseHost) < ROMSize)
261     return SIGSEGV_RETURN_SKIP_INSTRUCTION;
262    
263     // Ignore all other faults, if requested
264     if (PrefsFindBool("ignoresegv"))
265     return SIGSEGV_RETURN_SKIP_INSTRUCTION;
266     #endif
267    
268     return SIGSEGV_RETURN_FAILURE;
269     }
270    
271     /*
272 gbeauche 1.47 * Dump state when everything went wrong after a SEGV
273     */
274    
275 gbeauche 1.78 static void sigsegv_dump_state(sigsegv_info_t *sip)
276 gbeauche 1.47 {
277 gbeauche 1.78 const sigsegv_address_t fault_address = sigsegv_get_fault_address(sip);
278     const sigsegv_address_t fault_instruction = sigsegv_get_fault_instruction_address(sip);
279 gbeauche 1.50 fprintf(stderr, "Caught SIGSEGV at address %p", fault_address);
280 gbeauche 1.78 if (fault_instruction != SIGSEGV_INVALID_ADDRESS)
281 gbeauche 1.47 fprintf(stderr, " [IP=%p]", fault_instruction);
282     fprintf(stderr, "\n");
283     #if EMULATED_68K
284     uaecptr nextpc;
285     extern void m68k_dumpstate(uaecptr *nextpc);
286     m68k_dumpstate(&nextpc);
287     #endif
288 gbeauche 1.50 #if USE_JIT && JIT_DEBUG
289     extern void compiler_dumpstate(void);
290     compiler_dumpstate();
291     #endif
292 gbeauche 1.47 VideoQuitFullScreen();
293     #ifdef ENABLE_MON
294     char *arg[4] = {"mon", "-m", "-r", NULL};
295     mon(3, arg);
296 gbeauche 1.66 #endif
297 gbeauche 1.47 QuitEmulator();
298     }
299    
300    
301     /*
302 gbeauche 1.67 * Update virtual clock and trigger interrupts if necessary
303     */
304    
305     #ifdef USE_CPU_EMUL_SERVICES
306     static uint64 n_check_ticks = 0;
307     static uint64 emulated_ticks_start = 0;
308     static uint64 emulated_ticks_count = 0;
309     static int64 emulated_ticks_current = 0;
310     static int32 emulated_ticks_quantum = 1000;
311     int32 emulated_ticks = emulated_ticks_quantum;
312    
313     void cpu_do_check_ticks(void)
314     {
315     #if DEBUG
316     n_check_ticks++;
317     #endif
318    
319     uint64 now;
320     static uint64 next = 0;
321     if (next == 0)
322     next = emulated_ticks_start = GetTicks_usec();
323    
324     // Update total instructions count
325     if (emulated_ticks <= 0) {
326     emulated_ticks_current += (emulated_ticks_quantum - emulated_ticks);
327     // XXX: can you really have a machine fast enough to overflow
328     // a 63-bit m68k instruction counter within 16 ms?
329     if (emulated_ticks_current < 0) {
330     printf("WARNING: Overflowed 63-bit m68k instruction counter in less than 16 ms!\n");
331     goto recalibrate_quantum;
332     }
333     }
334    
335     // Check for interrupt opportunity
336     now = GetTicks_usec();
337     if (next < now) {
338     one_tick();
339     do {
340     next += 16625;
341     } while (next < now);
342     emulated_ticks_count++;
343    
344     // Recalibrate 1000 Hz quantum every 10 ticks
345     static uint64 last = 0;
346     if (last == 0)
347     last = now;
348     else if (now - last > 166250) {
349     recalibrate_quantum:
350     emulated_ticks_quantum = ((uint64)emulated_ticks_current * 1000) / (now - last);
351     emulated_ticks_current = 0;
352     last = now;
353     }
354     }
355    
356     // Update countdown
357     if (emulated_ticks <= 0)
358     emulated_ticks += emulated_ticks_quantum;
359     }
360     #endif
361    
362    
363     /*
364 cebix 1.1 * Main program
365     */
366    
367 cebix 1.32 static void usage(const char *prg_name)
368     {
369 cebix 1.48 printf(
370     "Usage: %s [OPTION...]\n"
371     "\nUnix options:\n"
372     " --config FILE\n read/write configuration from/to FILE\n"
373     " --display STRING\n X display to use\n"
374     " --break ADDRESS\n set ROM breakpoint\n"
375     " --rominfo\n dump ROM information\n", prg_name
376     );
377     LoadPrefs(); // read the prefs file so PrefsPrintUsage() will print the correct default values
378 cebix 1.32 PrefsPrintUsage();
379     exit(0);
380     }
381    
382 cebix 1.1 int main(int argc, char **argv)
383     {
384 cebix 1.12 char str[256];
385    
386 cebix 1.1 // Initialize variables
387     RAMBaseHost = NULL;
388     ROMBaseHost = NULL;
389     srand(time(NULL));
390     tzset();
391    
392     // Print some info
393     printf(GetString(STR_ABOUT_TEXT1), VERSION_MAJOR, VERSION_MINOR);
394     printf(" %s\n", GetString(STR_ABOUT_TEXT2));
395    
396 cebix 1.48 // Parse command line arguments
397     for (int i=1; i<argc; i++) {
398     if (strcmp(argv[i], "--help") == 0) {
399     usage(argv[0]);
400 gbeauche 1.59 #ifndef USE_SDL_VIDEO
401 cebix 1.48 } else if (strcmp(argv[i], "--display") == 0) {
402     i++; // don't remove the argument, gtk_init() needs it too
403     if (i < argc)
404     x_display_name = strdup(argv[i]);
405 gbeauche 1.59 #endif
406 gbeauche 1.74 } else if (strcmp(argv[i], "--gui-connection") == 0) {
407     argv[i++] = NULL;
408     if (i < argc) {
409     gui_connection_path = argv[i];
410     argv[i] = NULL;
411     }
412 cebix 1.48 } else if (strcmp(argv[i], "--break") == 0) {
413     argv[i++] = NULL;
414     if (i < argc) {
415     ROMBreakpoint = strtol(argv[i], NULL, 0);
416     argv[i] = NULL;
417     }
418     } else if (strcmp(argv[i], "--config") == 0) {
419     argv[i++] = NULL;
420     if (i < argc) {
421     extern string UserPrefsPath; // from prefs_unix.cpp
422     UserPrefsPath = argv[i];
423     argv[i] = NULL;
424     }
425     } else if (strcmp(argv[i], "--rominfo") == 0) {
426     argv[i] = NULL;
427     PrintROMInfo = true;
428     }
429     }
430    
431     // Remove processed arguments
432     for (int i=1; i<argc; i++) {
433     int k;
434     for (k=i; k<argc; k++)
435     if (argv[k] != NULL)
436     break;
437     if (k > i) {
438     k -= i;
439     for (int j=i+k; j<argc; j++)
440     argv[j-k] = argv[j];
441     argc -= k;
442     }
443     }
444    
445 gbeauche 1.75 // Connect to the external GUI
446 gbeauche 1.74 if (gui_connection_path) {
447     if ((gui_connection = rpc_init_client(gui_connection_path)) == NULL) {
448     fprintf(stderr, "Failed to initialize RPC client connection to the GUI\n");
449     return 1;
450     }
451     }
452    
453 cebix 1.28 #ifdef ENABLE_GTK
454 gbeauche 1.75 if (!gui_connection) {
455 cebix 1.43 #ifdef HAVE_GNOMEUI
456 gbeauche 1.75 // Init GNOME/GTK
457     char version[16];
458     sprintf(version, "%d.%d", VERSION_MAJOR, VERSION_MINOR);
459     gnome_init("Basilisk II", version, argc, argv);
460 cebix 1.43 #else
461 gbeauche 1.75 // Init GTK
462     gtk_set_locale();
463     gtk_init(&argc, &argv);
464 cebix 1.43 #endif
465 gbeauche 1.75 }
466 cebix 1.28 #endif
467    
468 cebix 1.32 // Read preferences
469     PrefsInit(argc, argv);
470    
471 cebix 1.48 // Any command line arguments left?
472 cebix 1.1 for (int i=1; i<argc; i++) {
473 cebix 1.48 if (argv[i][0] == '-') {
474 cebix 1.32 fprintf(stderr, "Unrecognized option '%s'\n", argv[i]);
475     usage(argv[0]);
476 cebix 1.28 }
477 cebix 1.1 }
478    
479 gbeauche 1.59 #ifndef USE_SDL_VIDEO
480 cebix 1.1 // Open display
481     x_display = XOpenDisplay(x_display_name);
482     if (x_display == NULL) {
483     char str[256];
484     sprintf(str, GetString(STR_NO_XSERVER_ERR), XDisplayName(x_display_name));
485     ErrorAlert(str);
486     QuitEmulator();
487     }
488    
489 cebix 1.12 #if defined(ENABLE_XF86_DGA) && !defined(ENABLE_MON)
490 cebix 1.1 // Fork out, so we can return from fullscreen mode when things get ugly
491 cebix 1.2 XF86DGAForkApp(DefaultScreen(x_display));
492 cebix 1.1 #endif
493 gbeauche 1.59 #endif
494    
495     #ifdef USE_SDL
496     // Initialize SDL system
497     int sdl_flags = 0;
498     #ifdef USE_SDL_VIDEO
499     sdl_flags |= SDL_INIT_VIDEO;
500     #endif
501 gbeauche 1.61 #ifdef USE_SDL_AUDIO
502     sdl_flags |= SDL_INIT_AUDIO;
503     #endif
504 gbeauche 1.59 assert(sdl_flags != 0);
505     if (SDL_Init(sdl_flags) == -1) {
506     char str[256];
507     sprintf(str, "Could not initialize SDL: %s.\n", SDL_GetError());
508     ErrorAlert(str);
509     QuitEmulator();
510     }
511 gbeauche 1.60 atexit(SDL_Quit);
512 gbeauche 1.59 #endif
513 cebix 1.1
514     // Init system routines
515     SysInit();
516    
517     // Show preferences editor
518 gbeauche 1.75 if (!gui_connection && !PrefsFindBool("nogui"))
519 cebix 1.1 if (!PrefsEditor())
520     QuitEmulator();
521 gbeauche 1.46
522 gbeauche 1.54 // Install the handler for SIGSEGV
523 gbeauche 1.55 if (!sigsegv_install_handler(sigsegv_handler)) {
524     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGSEGV", strerror(errno));
525     ErrorAlert(str);
526     QuitEmulator();
527     }
528 gbeauche 1.54
529 gbeauche 1.47 // Register dump state function when we got mad after a segfault
530     sigsegv_set_dump_state(sigsegv_dump_state);
531 cebix 1.1
532 cebix 1.9 // Read RAM size
533 cebix 1.1 RAMSize = PrefsFindInt32("ramsize") & 0xfff00000; // Round down to 1MB boundary
534     if (RAMSize < 1024*1024) {
535     WarningAlert(GetString(STR_SMALL_RAM_WARN));
536     RAMSize = 1024*1024;
537     }
538 gbeauche 1.72 if (RAMSize > 1023*1024*1024) // Cap to 1023MB (APD crashes at 1GB)
539     RAMSize = 1023*1024*1024;
540 cebix 1.9
541 gbeauche 1.20 #if REAL_ADDRESSING || DIRECT_ADDRESSING
542 gbeauche 1.33 RAMSize = RAMSize & -getpagesize(); // Round down to page boundary
543 gbeauche 1.20 #endif
544 gbeauche 1.33
545     // Initialize VM system
546     vm_init();
547 gbeauche 1.20
548 cebix 1.12 #if REAL_ADDRESSING
549 gbeauche 1.33 // Flag: RAM and ROM are contigously allocated from address 0
550     bool memory_mapped_from_zero = false;
551 gbeauche 1.71
552     // Make sure to map RAM & ROM at address 0 only on platforms that
553     // supports linker scripts to relocate the Basilisk II executable
554     // above 0x70000000
555     #if HAVE_LINKER_SCRIPT
556     const bool can_map_all_memory = true;
557     #else
558 gbeauche 1.33 const bool can_map_all_memory = false;
559 gbeauche 1.20 #endif
560 gbeauche 1.33
561     // Try to allocate all memory from 0x0000, if it is not known to crash
562 gbeauche 1.71 if (can_map_all_memory && (vm_acquire_mac_fixed(0, RAMSize + 0x100000) == 0)) {
563 gbeauche 1.20 D(bug("Could allocate RAM and ROM from 0x0000\n"));
564     memory_mapped_from_zero = true;
565     }
566 gbeauche 1.33
567 gbeauche 1.56 #ifndef PAGEZERO_HACK
568 gbeauche 1.33 // Otherwise, just create the Low Memory area (0x0000..0x2000)
569 gbeauche 1.71 else if (vm_acquire_mac_fixed(0, 0x2000) == 0) {
570 gbeauche 1.20 D(bug("Could allocate the Low Memory globals\n"));
571     lm_area_mapped = true;
572     }
573 gbeauche 1.33
574     // Exit on failure
575 gbeauche 1.20 else {
576 cebix 1.12 sprintf(str, GetString(STR_LOW_MEM_MMAP_ERR), strerror(errno));
577     ErrorAlert(str);
578     QuitEmulator();
579     }
580     #endif
581 gbeauche 1.56 #endif /* REAL_ADDRESSING */
582 cebix 1.12
583 cebix 1.9 // Create areas for Mac RAM and ROM
584 gbeauche 1.20 #if REAL_ADDRESSING
585     if (memory_mapped_from_zero) {
586     RAMBaseHost = (uint8 *)0;
587 gbeauche 1.33 ROMBaseHost = RAMBaseHost + RAMSize;
588 gbeauche 1.20 }
589     else
590     #endif
591     {
592 gbeauche 1.69 uint8 *ram_rom_area = (uint8 *)vm_acquire_mac(RAMSize + 0x100000);
593     if (ram_rom_area == VM_MAP_FAILED) {
594 cebix 1.36 ErrorAlert(STR_NO_MEM_ERR);
595 gbeauche 1.20 QuitEmulator();
596     }
597 gbeauche 1.69 RAMBaseHost = ram_rom_area;
598     ROMBaseHost = RAMBaseHost + RAMSize;
599 gbeauche 1.20 }
600 gbeauche 1.38
601     #if USE_SCRATCHMEM_SUBTERFUGE
602     // Allocate scratch memory
603 gbeauche 1.72 ScratchMem = (uint8 *)vm_acquire_mac(SCRATCH_MEM_SIZE);
604 gbeauche 1.38 if (ScratchMem == VM_MAP_FAILED) {
605     ErrorAlert(STR_NO_MEM_ERR);
606     QuitEmulator();
607     }
608     ScratchMem += SCRATCH_MEM_SIZE/2; // ScratchMem points to middle of block
609     #endif
610 cebix 1.22
611 gbeauche 1.20 #if DIRECT_ADDRESSING
612 gbeauche 1.33 // RAMBaseMac shall always be zero
613     MEMBaseDiff = (uintptr)RAMBaseHost;
614 gbeauche 1.20 RAMBaseMac = 0;
615 gbeauche 1.33 ROMBaseMac = Host2MacAddr(ROMBaseHost);
616 gbeauche 1.20 #endif
617 gbeauche 1.33 #if REAL_ADDRESSING
618 gbeauche 1.71 RAMBaseMac = Host2MacAddr(RAMBaseHost);
619     ROMBaseMac = Host2MacAddr(ROMBaseHost);
620 cebix 1.12 #endif
621     D(bug("Mac RAM starts at %p (%08x)\n", RAMBaseHost, RAMBaseMac));
622     D(bug("Mac ROM starts at %p (%08x)\n", ROMBaseHost, ROMBaseMac));
623 gbeauche 1.20
624 cebix 1.1 // Get rom file path from preferences
625     const char *rom_path = PrefsFindString("rom");
626    
627     // Load Mac ROM
628     int rom_fd = open(rom_path ? rom_path : ROM_FILE_NAME, O_RDONLY);
629     if (rom_fd < 0) {
630 cebix 1.36 ErrorAlert(STR_NO_ROM_FILE_ERR);
631 cebix 1.1 QuitEmulator();
632     }
633     printf(GetString(STR_READING_ROM_FILE));
634     ROMSize = lseek(rom_fd, 0, SEEK_END);
635     if (ROMSize != 64*1024 && ROMSize != 128*1024 && ROMSize != 256*1024 && ROMSize != 512*1024 && ROMSize != 1024*1024) {
636 cebix 1.36 ErrorAlert(STR_ROM_SIZE_ERR);
637 cebix 1.1 close(rom_fd);
638     QuitEmulator();
639     }
640     lseek(rom_fd, 0, SEEK_SET);
641     if (read(rom_fd, ROMBaseHost, ROMSize) != (ssize_t)ROMSize) {
642 cebix 1.36 ErrorAlert(STR_ROM_FILE_READ_ERR);
643 cebix 1.1 close(rom_fd);
644     QuitEmulator();
645     }
646    
647 cebix 1.12 #if !EMULATED_68K
648     // Get CPU model
649     int mib[2] = {CTL_HW, HW_MODEL};
650     char *model;
651     size_t model_len;
652     sysctl(mib, 2, NULL, &model_len, NULL, 0);
653     model = (char *)malloc(model_len);
654     sysctl(mib, 2, model, &model_len, NULL, 0);
655     D(bug("Model: %s\n", model));
656    
657     // Set CPU and FPU type
658     CPUIs68060 = false;
659     if (strstr(model, "020"))
660     CPUType = 2;
661     else if (strstr(model, "030"))
662     CPUType = 3;
663     else if (strstr(model, "040"))
664     CPUType = 4;
665     else if (strstr(model, "060")) {
666     CPUType = 4;
667     CPUIs68060 = true;
668     } else {
669     printf("WARNING: Cannot detect CPU type, assuming 68020\n");
670     CPUType = 2;
671     }
672 cebix 1.24 FPUType = 1; // NetBSD has an FPU emulation, so the FPU ought to be available at all times
673 cebix 1.12 TwentyFourBitAddressing = false;
674     #endif
675    
676 cebix 1.3 // Initialize everything
677     if (!InitAll())
678 cebix 1.1 QuitEmulator();
679 cebix 1.12 D(bug("Initialization complete\n"));
680    
681 gbeauche 1.51 #if !EMULATED_68K
682     // (Virtual) supervisor mode, disable interrupts
683     EmulatedSR = 0x2700;
684    
685 cebix 1.12 #ifdef HAVE_PTHREADS
686     // Get handle of main thread
687     emul_thread = pthread_self();
688     #endif
689    
690     // Create and install stack for signal handlers
691     sig_stack = malloc(SIG_STACK_SIZE);
692     D(bug("Signal stack at %p\n", sig_stack));
693     if (sig_stack == NULL) {
694 cebix 1.36 ErrorAlert(STR_NOT_ENOUGH_MEMORY_ERR);
695 cebix 1.12 QuitEmulator();
696     }
697     stack_t new_stack;
698     new_stack.ss_sp = sig_stack;
699     new_stack.ss_flags = 0;
700     new_stack.ss_size = SIG_STACK_SIZE;
701     if (sigaltstack(&new_stack, NULL) < 0) {
702     sprintf(str, GetString(STR_SIGALTSTACK_ERR), strerror(errno));
703     ErrorAlert(str);
704     QuitEmulator();
705     }
706    
707     // Install SIGILL handler for emulating privileged instructions and
708     // executing A-Trap and EMUL_OP opcodes
709     sigemptyset(&sigill_sa.sa_mask); // Block virtual 68k interrupts during SIGILL handling
710     sigaddset(&sigill_sa.sa_mask, SIG_IRQ);
711     sigaddset(&sigill_sa.sa_mask, SIGALRM);
712     sigill_sa.sa_handler = (void (*)(int))sigill_handler;
713     sigill_sa.sa_flags = SA_ONSTACK;
714     if (sigaction(SIGILL, &sigill_sa, NULL) < 0) {
715     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGILL", strerror(errno));
716     ErrorAlert(str);
717     QuitEmulator();
718     }
719    
720     // Install virtual 68k interrupt signal handler
721     sigemptyset(&sigirq_sa.sa_mask);
722     sigaddset(&sigirq_sa.sa_mask, SIGALRM);
723     sigirq_sa.sa_handler = (void (*)(int))sigirq_handler;
724     sigirq_sa.sa_flags = SA_ONSTACK | SA_RESTART;
725     if (sigaction(SIG_IRQ, &sigirq_sa, NULL) < 0) {
726     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_IRQ", strerror(errno));
727     ErrorAlert(str);
728     QuitEmulator();
729     }
730     #endif
731 cebix 1.1
732 cebix 1.12 #ifdef ENABLE_MON
733     // Setup SIGINT handler to enter mon
734     sigemptyset(&sigint_sa.sa_mask);
735 cebix 1.21 sigint_sa.sa_handler = (void (*)(int))sigint_handler;
736 cebix 1.12 sigint_sa.sa_flags = 0;
737     sigaction(SIGINT, &sigint_sa, NULL);
738     #endif
739 cebix 1.1
740 gbeauche 1.67 #ifndef USE_CPU_EMUL_SERVICES
741 cebix 1.39 #if defined(HAVE_PTHREADS)
742    
743     // POSIX threads available, start 60Hz thread
744 cebix 1.44 Set_pthread_attr(&tick_thread_attr, 0);
745 cebix 1.39 tick_thread_active = (pthread_create(&tick_thread, &tick_thread_attr, tick_func, NULL) == 0);
746     if (!tick_thread_active) {
747     sprintf(str, GetString(STR_TICK_THREAD_ERR), strerror(errno));
748     ErrorAlert(str);
749     QuitEmulator();
750     }
751     D(bug("60Hz thread started\n"));
752    
753     #elif defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
754 cebix 1.12
755     // POSIX.4 timers and real-time signals available, start 60Hz timer
756 cebix 1.1 sigemptyset(&timer_sa.sa_mask);
757 cebix 1.19 timer_sa.sa_sigaction = (void (*)(int, siginfo_t *, void *))one_tick;
758 cebix 1.1 timer_sa.sa_flags = SA_SIGINFO | SA_RESTART;
759     if (sigaction(SIG_TIMER, &timer_sa, NULL) < 0) {
760 cebix 1.12 sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIG_TIMER", strerror(errno));
761     ErrorAlert(str);
762 cebix 1.1 QuitEmulator();
763     }
764     struct sigevent timer_event;
765     timer_event.sigev_notify = SIGEV_SIGNAL;
766     timer_event.sigev_signo = SIG_TIMER;
767     if (timer_create(CLOCK_REALTIME, &timer_event, &timer) < 0) {
768 cebix 1.12 sprintf(str, GetString(STR_TIMER_CREATE_ERR), strerror(errno));
769     ErrorAlert(str);
770 cebix 1.1 QuitEmulator();
771     }
772     struct itimerspec req;
773     req.it_value.tv_sec = 0;
774     req.it_value.tv_nsec = 16625000;
775     req.it_interval.tv_sec = 0;
776     req.it_interval.tv_nsec = 16625000;
777 cebix 1.10 if (timer_settime(timer, 0, &req, NULL) < 0) {
778 cebix 1.12 sprintf(str, GetString(STR_TIMER_SETTIME_ERR), strerror(errno));
779     ErrorAlert(str);
780 cebix 1.1 QuitEmulator();
781     }
782 cebix 1.12 D(bug("60Hz timer started\n"));
783 cebix 1.1
784 cebix 1.12 #else
785    
786     // Start 60Hz timer
787     sigemptyset(&timer_sa.sa_mask); // Block virtual 68k interrupts during SIGARLM handling
788 cebix 1.53 #if !EMULATED_68K
789 cebix 1.12 sigaddset(&timer_sa.sa_mask, SIG_IRQ);
790 cebix 1.53 #endif
791 cebix 1.12 timer_sa.sa_handler = one_tick;
792     timer_sa.sa_flags = SA_ONSTACK | SA_RESTART;
793     if (sigaction(SIGALRM, &timer_sa, NULL) < 0) {
794     sprintf(str, GetString(STR_SIG_INSTALL_ERR), "SIGALRM", strerror(errno));
795     ErrorAlert(str);
796 cebix 1.1 QuitEmulator();
797     }
798 cebix 1.12 struct itimerval req;
799     req.it_interval.tv_sec = req.it_value.tv_sec = 0;
800     req.it_interval.tv_usec = req.it_value.tv_usec = 16625;
801     setitimer(ITIMER_REAL, &req, NULL);
802    
803 cebix 1.1 #endif
804 gbeauche 1.67 #endif
805 cebix 1.1
806 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
807 cebix 1.12 // Start XPRAM watchdog thread
808 cebix 1.41 memcpy(last_xpram, XPRAM, XPRAM_SIZE);
809 cebix 1.12 xpram_thread_active = (pthread_create(&xpram_thread, NULL, xpram_func, NULL) == 0);
810     D(bug("XPRAM thread started\n"));
811 cebix 1.4 #endif
812    
813 cebix 1.1 // Start 68k and jump to ROM boot routine
814 cebix 1.12 D(bug("Starting emulation...\n"));
815 cebix 1.1 Start680x0();
816    
817     QuitEmulator();
818     return 0;
819     }
820    
821    
822     /*
823     * Quit emulator
824     */
825    
826     void QuitEmulator(void)
827     {
828 cebix 1.12 D(bug("QuitEmulator\n"));
829    
830     #if EMULATED_68K
831 cebix 1.1 // Exit 680x0 emulation
832     Exit680x0();
833 cebix 1.12 #endif
834 cebix 1.1
835 gbeauche 1.67 #if defined(USE_CPU_EMUL_SERVICES)
836     // Show statistics
837     uint64 emulated_ticks_end = GetTicks_usec();
838     D(bug("%ld ticks in %ld usec = %f ticks/sec [%ld tick checks]\n",
839     (long)emulated_ticks_count, (long)(emulated_ticks_end - emulated_ticks_start),
840     emulated_ticks_count * 1000000.0 / (emulated_ticks_end - emulated_ticks_start), (long)n_check_ticks));
841     #elif defined(USE_PTHREADS_SERVICES)
842 cebix 1.1 // Stop 60Hz thread
843     if (tick_thread_active) {
844     tick_thread_cancel = true;
845     #ifdef HAVE_PTHREAD_CANCEL
846     pthread_cancel(tick_thread);
847     #endif
848     pthread_join(tick_thread, NULL);
849     }
850 cebix 1.39 #elif defined(HAVE_TIMER_CREATE) && defined(_POSIX_REALTIME_SIGNALS)
851     // Stop 60Hz timer
852     timer_delete(timer);
853 cebix 1.12 #else
854     struct itimerval req;
855     req.it_interval.tv_sec = req.it_value.tv_sec = 0;
856     req.it_interval.tv_usec = req.it_value.tv_usec = 0;
857     setitimer(ITIMER_REAL, &req, NULL);
858 cebix 1.1 #endif
859    
860 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
861 cebix 1.1 // Stop XPRAM watchdog thread
862     if (xpram_thread_active) {
863     xpram_thread_cancel = true;
864     #ifdef HAVE_PTHREAD_CANCEL
865     pthread_cancel(xpram_thread);
866     #endif
867     pthread_join(xpram_thread, NULL);
868     }
869 cebix 1.12 #endif
870 cebix 1.1
871 cebix 1.3 // Deinitialize everything
872     ExitAll();
873 cebix 1.1
874 cebix 1.22 // Free ROM/RAM areas
875 gbeauche 1.33 if (RAMBaseHost != VM_MAP_FAILED) {
876 gbeauche 1.69 vm_release(RAMBaseHost, RAMSize + 0x100000);
877 cebix 1.22 RAMBaseHost = NULL;
878 cebix 1.17 ROMBaseHost = NULL;
879     }
880 cebix 1.1
881 cebix 1.22 #if USE_SCRATCHMEM_SUBTERFUGE
882 cebix 1.12 // Delete scratch memory area
883 gbeauche 1.33 if (ScratchMem != (uint8 *)VM_MAP_FAILED) {
884     vm_release((void *)(ScratchMem - SCRATCH_MEM_SIZE/2), SCRATCH_MEM_SIZE);
885 cebix 1.17 ScratchMem = NULL;
886     }
887 cebix 1.12 #endif
888    
889     #if REAL_ADDRESSING
890     // Delete Low Memory area
891     if (lm_area_mapped)
892 gbeauche 1.33 vm_release(0, 0x2000);
893 cebix 1.12 #endif
894 gbeauche 1.33
895     // Exit VM wrappers
896     vm_exit();
897 cebix 1.12
898 cebix 1.1 // Exit system routines
899     SysExit();
900    
901     // Exit preferences
902     PrefsExit();
903    
904     // Close X11 server connection
905 gbeauche 1.60 #ifndef USE_SDL_VIDEO
906 cebix 1.1 if (x_display)
907     XCloseDisplay(x_display);
908 gbeauche 1.59 #endif
909 cebix 1.1
910 gbeauche 1.74 // Notify GUI we are about to leave
911     if (gui_connection) {
912     if (rpc_method_invoke(gui_connection, RPC_METHOD_EXIT, RPC_TYPE_INVALID) == RPC_ERROR_NO_ERROR)
913     rpc_method_wait_for_reply(gui_connection, RPC_TYPE_INVALID);
914     }
915    
916 cebix 1.1 exit(0);
917     }
918    
919    
920     /*
921     * Code was patched, flush caches if neccessary (i.e. when using a real 680x0
922     * or a dynamically recompiling emulator)
923     */
924    
925     void FlushCodeCache(void *start, uint32 size)
926     {
927 gbeauche 1.50 #if USE_JIT
928     if (UseJIT)
929 gbeauche 1.76 flush_icache_range((uint8 *)start, size);
930 gbeauche 1.50 #endif
931 cebix 1.12 #if !EMULATED_68K && defined(__NetBSD__)
932     m68k_sync_icache(start, size);
933     #endif
934 cebix 1.4 }
935    
936    
937     /*
938     * SIGINT handler, enters mon
939     */
940    
941 cebix 1.12 #ifdef ENABLE_MON
942 cebix 1.4 static void sigint_handler(...)
943     {
944 cebix 1.12 #if EMULATED_68K
945 cebix 1.8 uaecptr nextpc;
946 cebix 1.12 extern void m68k_dumpstate(uaecptr *nextpc);
947 cebix 1.8 m68k_dumpstate(&nextpc);
948 cebix 1.34 #endif
949 cebix 1.37 VideoQuitFullScreen();
950 cebix 1.21 char *arg[4] = {"mon", "-m", "-r", NULL};
951     mon(3, arg);
952 cebix 1.4 QuitEmulator();
953 cebix 1.1 }
954     #endif
955    
956    
957 cebix 1.44 #ifdef HAVE_PTHREADS
958     /*
959 cebix 1.45 * Pthread configuration
960 cebix 1.44 */
961 cebix 1.45
962     void Set_pthread_attr(pthread_attr_t *attr, int priority)
963 cebix 1.44 {
964     pthread_attr_init(attr);
965     #if defined(_POSIX_THREAD_PRIORITY_SCHEDULING)
966     // Some of these only work for superuser
967     if (geteuid() == 0) {
968     pthread_attr_setinheritsched(attr, PTHREAD_EXPLICIT_SCHED);
969     pthread_attr_setschedpolicy(attr, SCHED_FIFO);
970     struct sched_param fifo_param;
971     fifo_param.sched_priority = ((sched_get_priority_min(SCHED_FIFO) +
972     sched_get_priority_max(SCHED_FIFO)) / 2 +
973     priority);
974     pthread_attr_setschedparam(attr, &fifo_param);
975     }
976     if (pthread_attr_setscope(attr, PTHREAD_SCOPE_SYSTEM) != 0) {
977     #ifdef PTHREAD_SCOPE_BOUND_NP
978     // If system scope is not available (eg. we're not running
979     // with CAP_SCHED_MGT capability on an SGI box), try bound
980     // scope. It exposes pthread scheduling to the kernel,
981     // without setting realtime priority.
982     pthread_attr_setscope(attr, PTHREAD_SCOPE_BOUND_NP);
983     #endif
984     }
985     #endif
986     }
987     #endif // HAVE_PTHREADS
988    
989    
990 cebix 1.1 /*
991 cebix 1.37 * Mutexes
992     */
993    
994     #ifdef HAVE_PTHREADS
995    
996     struct B2_mutex {
997 cebix 1.44 B2_mutex() {
998     pthread_mutexattr_t attr;
999     pthread_mutexattr_init(&attr);
1000     // Initialize the mutex for priority inheritance --
1001     // required for accurate timing.
1002 gbeauche 1.63 #if defined(HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL) && !defined(__CYGWIN__)
1003 cebix 1.44 pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT);
1004     #endif
1005     #if defined(HAVE_PTHREAD_MUTEXATTR_SETTYPE) && defined(PTHREAD_MUTEX_NORMAL)
1006     pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL);
1007     #endif
1008 gbeauche 1.49 #ifdef HAVE_PTHREAD_MUTEXATTR_SETPSHARED
1009 cebix 1.44 pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_PRIVATE);
1010 gbeauche 1.49 #endif
1011 cebix 1.44 pthread_mutex_init(&m, &attr);
1012     pthread_mutexattr_destroy(&attr);
1013     }
1014 gbeauche 1.51 ~B2_mutex() {
1015     pthread_mutex_trylock(&m); // Make sure it's locked before
1016     pthread_mutex_unlock(&m); // unlocking it.
1017     pthread_mutex_destroy(&m);
1018     }
1019 cebix 1.37 pthread_mutex_t m;
1020     };
1021    
1022     B2_mutex *B2_create_mutex(void)
1023     {
1024     return new B2_mutex;
1025     }
1026    
1027     void B2_lock_mutex(B2_mutex *mutex)
1028     {
1029     pthread_mutex_lock(&mutex->m);
1030     }
1031    
1032     void B2_unlock_mutex(B2_mutex *mutex)
1033     {
1034     pthread_mutex_unlock(&mutex->m);
1035     }
1036    
1037     void B2_delete_mutex(B2_mutex *mutex)
1038     {
1039     delete mutex;
1040     }
1041    
1042     #else
1043    
1044     struct B2_mutex {
1045     int dummy;
1046     };
1047    
1048     B2_mutex *B2_create_mutex(void)
1049     {
1050     return new B2_mutex;
1051     }
1052    
1053     void B2_lock_mutex(B2_mutex *mutex)
1054     {
1055     }
1056    
1057     void B2_unlock_mutex(B2_mutex *mutex)
1058     {
1059     }
1060    
1061     void B2_delete_mutex(B2_mutex *mutex)
1062     {
1063     delete mutex;
1064     }
1065    
1066     #endif
1067    
1068    
1069     /*
1070 cebix 1.1 * Interrupt flags (must be handled atomically!)
1071     */
1072    
1073     uint32 InterruptFlags = 0;
1074    
1075 cebix 1.12 #if EMULATED_68K
1076 cebix 1.1 void SetInterruptFlag(uint32 flag)
1077     {
1078 cebix 1.37 LOCK_INTFLAGS;
1079 cebix 1.1 InterruptFlags |= flag;
1080 cebix 1.37 UNLOCK_INTFLAGS;
1081 cebix 1.1 }
1082    
1083     void ClearInterruptFlag(uint32 flag)
1084     {
1085 cebix 1.37 LOCK_INTFLAGS;
1086 cebix 1.1 InterruptFlags &= ~flag;
1087 cebix 1.37 UNLOCK_INTFLAGS;
1088 cebix 1.12 }
1089     #endif
1090    
1091     #if !EMULATED_68K
1092     void TriggerInterrupt(void)
1093     {
1094     #if defined(HAVE_PTHREADS)
1095     pthread_kill(emul_thread, SIG_IRQ);
1096     #else
1097     raise(SIG_IRQ);
1098     #endif
1099 cebix 1.22 }
1100    
1101     void TriggerNMI(void)
1102     {
1103     // not yet supported
1104 cebix 1.12 }
1105     #endif
1106    
1107    
1108     /*
1109     * XPRAM watchdog thread (saves XPRAM every minute)
1110     */
1111    
1112     static void xpram_watchdog(void)
1113     {
1114 cebix 1.41 if (memcmp(last_xpram, XPRAM, XPRAM_SIZE)) {
1115     memcpy(last_xpram, XPRAM, XPRAM_SIZE);
1116 cebix 1.12 SaveXPRAM();
1117     }
1118     }
1119    
1120 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
1121 cebix 1.12 static void *xpram_func(void *arg)
1122     {
1123     while (!xpram_thread_cancel) {
1124 cebix 1.16 for (int i=0; i<60 && !xpram_thread_cancel; i++)
1125 cebix 1.29 Delay_usec(999999); // Only wait 1 second so we quit promptly when xpram_thread_cancel becomes true
1126 cebix 1.12 xpram_watchdog();
1127     }
1128     return NULL;
1129 cebix 1.1 }
1130 cebix 1.12 #endif
1131 cebix 1.1
1132    
1133     /*
1134     * 60Hz thread (really 60.15Hz)
1135     */
1136    
1137 cebix 1.12 static void one_second(void)
1138     {
1139     // Pseudo Mac 1Hz interrupt, update local time
1140     WriteMacInt32(0x20c, TimerDateTime());
1141    
1142 cebix 1.18 SetInterruptFlag(INTFLAG_1HZ);
1143 cebix 1.14 TriggerInterrupt();
1144    
1145 gbeauche 1.67 #ifndef USE_PTHREADS_SERVICES
1146 cebix 1.12 static int second_counter = 0;
1147     if (++second_counter > 60) {
1148     second_counter = 0;
1149     xpram_watchdog();
1150     }
1151     #endif
1152     }
1153    
1154 cebix 1.1 static void one_tick(...)
1155     {
1156     static int tick_counter = 0;
1157     if (++tick_counter > 60) {
1158     tick_counter = 0;
1159 cebix 1.12 one_second();
1160 cebix 1.1 }
1161    
1162 gbeauche 1.70 #ifndef USE_PTHREADS_SERVICES
1163     // Threads not used to trigger interrupts, perform video refresh from here
1164 cebix 1.12 VideoRefresh();
1165 gbeauche 1.70 #endif
1166    
1167     #ifndef HAVE_PTHREADS
1168     // No threads available, perform networking from here
1169 cebix 1.40 SetInterruptFlag(INTFLAG_ETHER);
1170 cebix 1.12 #endif
1171    
1172 cebix 1.1 // Trigger 60Hz interrupt
1173     if (ROMVersion != ROM_VERSION_CLASSIC || HasMacStarted()) {
1174     SetInterruptFlag(INTFLAG_60HZ);
1175     TriggerInterrupt();
1176     }
1177     }
1178    
1179 gbeauche 1.67 #ifdef USE_PTHREADS_SERVICES
1180 cebix 1.1 static void *tick_func(void *arg)
1181     {
1182 cebix 1.39 uint64 start = GetTicks_usec();
1183     int64 ticks = 0;
1184 cebix 1.16 uint64 next = GetTicks_usec();
1185 cebix 1.1 while (!tick_thread_cancel) {
1186 cebix 1.16 one_tick();
1187     next += 16625;
1188     int64 delay = next - GetTicks_usec();
1189     if (delay > 0)
1190     Delay_usec(delay);
1191     else if (delay < -16625)
1192     next = GetTicks_usec();
1193 cebix 1.39 ticks++;
1194 cebix 1.16 }
1195 cebix 1.39 uint64 end = GetTicks_usec();
1196 gbeauche 1.68 D(bug("%lld ticks in %lld usec = %f ticks/sec\n", ticks, end - start, ticks * 1000000.0 / (end - start)));
1197 cebix 1.16 return NULL;
1198     }
1199     #endif
1200 cebix 1.12
1201    
1202     #if !EMULATED_68K
1203     /*
1204     * Virtual 68k interrupt handler
1205     */
1206    
1207     static void sigirq_handler(int sig, int code, struct sigcontext *scp)
1208     {
1209     // Interrupts disabled? Then do nothing
1210     if (EmulatedSR & 0x0700)
1211     return;
1212    
1213     struct sigstate *state = (struct sigstate *)scp->sc_ap;
1214     M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
1215    
1216     // Set up interrupt frame on stack
1217     uint32 a7 = regs->a[7];
1218     a7 -= 2;
1219     WriteMacInt16(a7, 0x64);
1220     a7 -= 4;
1221     WriteMacInt32(a7, scp->sc_pc);
1222     a7 -= 2;
1223     WriteMacInt16(a7, scp->sc_ps | EmulatedSR);
1224     scp->sc_sp = regs->a[7] = a7;
1225    
1226     // Set interrupt level
1227     EmulatedSR |= 0x2100;
1228    
1229     // Jump to MacOS interrupt handler on return
1230     scp->sc_pc = ReadMacInt32(0x64);
1231     }
1232 cebix 1.1
1233    
1234     /*
1235 cebix 1.12 * SIGILL handler, for emulation of privileged instructions and executing
1236     * A-Trap and EMUL_OP opcodes
1237 cebix 1.1 */
1238    
1239 cebix 1.12 static void sigill_handler(int sig, int code, struct sigcontext *scp)
1240 cebix 1.1 {
1241 cebix 1.12 struct sigstate *state = (struct sigstate *)scp->sc_ap;
1242     uint16 *pc = (uint16 *)scp->sc_pc;
1243     uint16 opcode = *pc;
1244     M68kRegisters *regs = (M68kRegisters *)&state->ss_frame;
1245    
1246     #define INC_PC(n) scp->sc_pc += (n)
1247    
1248     #define GET_SR (scp->sc_ps | EmulatedSR)
1249    
1250     #define STORE_SR(v) \
1251     scp->sc_ps = (v) & 0xff; \
1252 cebix 1.24 EmulatedSR = (v) & 0xe700; \
1253 cebix 1.12 if (((v) & 0x0700) == 0 && InterruptFlags) \
1254     TriggerInterrupt();
1255    
1256     //printf("opcode %04x at %p, sr %04x, emul_sr %04x\n", opcode, pc, scp->sc_ps, EmulatedSR);
1257    
1258     if ((opcode & 0xf000) == 0xa000) {
1259    
1260     // A-Line instruction, set up A-Line trap frame on stack
1261     uint32 a7 = regs->a[7];
1262     a7 -= 2;
1263     WriteMacInt16(a7, 0x28);
1264     a7 -= 4;
1265     WriteMacInt32(a7, (uint32)pc);
1266     a7 -= 2;
1267     WriteMacInt16(a7, GET_SR);
1268     scp->sc_sp = regs->a[7] = a7;
1269    
1270     // Jump to MacOS A-Line handler on return
1271     scp->sc_pc = ReadMacInt32(0x28);
1272    
1273     } else if ((opcode & 0xff00) == 0x7100) {
1274    
1275     // Extended opcode, push registers on user stack
1276     uint32 a7 = regs->a[7];
1277     a7 -= 4;
1278     WriteMacInt32(a7, (uint32)pc);
1279     a7 -= 2;
1280     WriteMacInt16(a7, scp->sc_ps);
1281     for (int i=7; i>=0; i--) {
1282     a7 -= 4;
1283     WriteMacInt32(a7, regs->a[i]);
1284     }
1285     for (int i=7; i>=0; i--) {
1286     a7 -= 4;
1287     WriteMacInt32(a7, regs->d[i]);
1288     }
1289     scp->sc_sp = regs->a[7] = a7;
1290    
1291     // Jump to EmulOp trampoline code on return
1292     scp->sc_pc = (uint32)EmulOpTrampoline;
1293    
1294     } else switch (opcode) { // Emulate privileged instructions
1295    
1296     case 0x40e7: // move sr,-(sp)
1297     regs->a[7] -= 2;
1298     WriteMacInt16(regs->a[7], GET_SR);
1299     scp->sc_sp = regs->a[7];
1300     INC_PC(2);
1301     break;
1302    
1303     case 0x46df: { // move (sp)+,sr
1304     uint16 sr = ReadMacInt16(regs->a[7]);
1305     STORE_SR(sr);
1306     regs->a[7] += 2;
1307     scp->sc_sp = regs->a[7];
1308     INC_PC(2);
1309     break;
1310     }
1311    
1312     case 0x007c: { // ori #xxxx,sr
1313     uint16 sr = GET_SR | pc[1];
1314     scp->sc_ps = sr & 0xff; // oring bits into the sr can't enable interrupts, so we don't need to call STORE_SR
1315 cebix 1.24 EmulatedSR = sr & 0xe700;
1316 cebix 1.12 INC_PC(4);
1317     break;
1318     }
1319    
1320     case 0x027c: { // andi #xxxx,sr
1321     uint16 sr = GET_SR & pc[1];
1322     STORE_SR(sr);
1323     INC_PC(4);
1324     break;
1325     }
1326    
1327     case 0x46fc: // move #xxxx,sr
1328     STORE_SR(pc[1]);
1329     INC_PC(4);
1330     break;
1331    
1332     case 0x46ef: { // move (xxxx,sp),sr
1333     uint16 sr = ReadMacInt16(regs->a[7] + (int32)(int16)pc[1]);
1334     STORE_SR(sr);
1335     INC_PC(4);
1336     break;
1337     }
1338    
1339     case 0x46d8: // move (a0)+,sr
1340     case 0x46d9: { // move (a1)+,sr
1341     uint16 sr = ReadMacInt16(regs->a[opcode & 7]);
1342     STORE_SR(sr);
1343     regs->a[opcode & 7] += 2;
1344     INC_PC(2);
1345     break;
1346     }
1347 cebix 1.1
1348 cebix 1.12 case 0x40f8: // move sr,xxxx.w
1349     WriteMacInt16(pc[1], GET_SR);
1350     INC_PC(4);
1351     break;
1352    
1353     case 0x40d0: // move sr,(a0)
1354     case 0x40d1: // move sr,(a1)
1355     case 0x40d2: // move sr,(a2)
1356     case 0x40d3: // move sr,(a3)
1357     case 0x40d4: // move sr,(a4)
1358     case 0x40d5: // move sr,(a5)
1359     case 0x40d6: // move sr,(a6)
1360     case 0x40d7: // move sr,(sp)
1361     WriteMacInt16(regs->a[opcode & 7], GET_SR);
1362     INC_PC(2);
1363     break;
1364    
1365     case 0x40c0: // move sr,d0
1366     case 0x40c1: // move sr,d1
1367     case 0x40c2: // move sr,d2
1368     case 0x40c3: // move sr,d3
1369     case 0x40c4: // move sr,d4
1370     case 0x40c5: // move sr,d5
1371     case 0x40c6: // move sr,d6
1372     case 0x40c7: // move sr,d7
1373     regs->d[opcode & 7] = GET_SR;
1374     INC_PC(2);
1375     break;
1376    
1377     case 0x46c0: // move d0,sr
1378     case 0x46c1: // move d1,sr
1379     case 0x46c2: // move d2,sr
1380     case 0x46c3: // move d3,sr
1381     case 0x46c4: // move d4,sr
1382     case 0x46c5: // move d5,sr
1383     case 0x46c6: // move d6,sr
1384     case 0x46c7: { // move d7,sr
1385     uint16 sr = regs->d[opcode & 7];
1386     STORE_SR(sr);
1387     INC_PC(2);
1388     break;
1389 cebix 1.1 }
1390 cebix 1.12
1391     case 0xf327: // fsave -(sp)
1392 cebix 1.35 regs->a[7] -= 4;
1393     WriteMacInt32(regs->a[7], 0x41000000); // Idle frame
1394 cebix 1.24 scp->sc_sp = regs->a[7];
1395     INC_PC(2);
1396     break;
1397 cebix 1.12
1398     case 0xf35f: // frestore (sp)+
1399 cebix 1.35 regs->a[7] += 4;
1400 cebix 1.24 scp->sc_sp = regs->a[7];
1401     INC_PC(2);
1402     break;
1403 cebix 1.12
1404 cebix 1.24 case 0x4e73: { // rte
1405 cebix 1.12 uint32 a7 = regs->a[7];
1406     uint16 sr = ReadMacInt16(a7);
1407     a7 += 2;
1408     scp->sc_ps = sr & 0xff;
1409 cebix 1.24 EmulatedSR = sr & 0xe700;
1410 cebix 1.12 scp->sc_pc = ReadMacInt32(a7);
1411 cebix 1.24 a7 += 4;
1412     uint16 format = ReadMacInt16(a7) >> 12;
1413     a7 += 2;
1414     static const int frame_adj[16] = {
1415     0, 0, 4, 4, 8, 0, 0, 52, 50, 12, 24, 84, 16, 0, 0, 0
1416     };
1417     scp->sc_sp = regs->a[7] = a7 + frame_adj[format];
1418 cebix 1.12 break;
1419 cebix 1.1 }
1420 cebix 1.12
1421     case 0x4e7a: // movec cr,x
1422     switch (pc[1]) {
1423     case 0x0002: // movec cacr,d0
1424     regs->d[0] = 0x3111;
1425     break;
1426     case 0x1002: // movec cacr,d1
1427     regs->d[1] = 0x3111;
1428     break;
1429     case 0x0003: // movec tc,d0
1430 cebix 1.24 case 0x0004: // movec itt0,d0
1431     case 0x0005: // movec itt1,d0
1432     case 0x0006: // movec dtt0,d0
1433     case 0x0007: // movec dtt1,d0
1434     case 0x0806: // movec urp,d0
1435     case 0x0807: // movec srp,d0
1436 cebix 1.12 regs->d[0] = 0;
1437     break;
1438 cebix 1.24 case 0x1000: // movec sfc,d1
1439     case 0x1001: // movec dfc,d1
1440 cebix 1.12 case 0x1003: // movec tc,d1
1441 cebix 1.24 case 0x1801: // movec vbr,d1
1442 cebix 1.12 regs->d[1] = 0;
1443     break;
1444 cebix 1.24 case 0x8801: // movec vbr,a0
1445     regs->a[0] = 0;
1446     break;
1447     case 0x9801: // movec vbr,a1
1448     regs->a[1] = 0;
1449     break;
1450 cebix 1.12 default:
1451     goto ill;
1452     }
1453     INC_PC(4);
1454     break;
1455    
1456     case 0x4e7b: // movec x,cr
1457     switch (pc[1]) {
1458 cebix 1.24 case 0x1000: // movec d1,sfc
1459     case 0x1001: // movec d1,dfc
1460 cebix 1.12 case 0x0801: // movec d0,vbr
1461 cebix 1.24 case 0x1801: // movec d1,vbr
1462 cebix 1.12 break;
1463     case 0x0002: // movec d0,cacr
1464     case 0x1002: // movec d1,cacr
1465     FlushCodeCache(NULL, 0);
1466     break;
1467     default:
1468     goto ill;
1469     }
1470     INC_PC(4);
1471     break;
1472    
1473     case 0xf478: // cpusha dc
1474     case 0xf4f8: // cpusha dc/ic
1475     FlushCodeCache(NULL, 0);
1476     INC_PC(2);
1477     break;
1478    
1479     default:
1480     ill: printf("SIGILL num %d, code %d\n", sig, code);
1481     printf(" context %p:\n", scp);
1482     printf(" onstack %08x\n", scp->sc_onstack);
1483     printf(" sp %08x\n", scp->sc_sp);
1484     printf(" fp %08x\n", scp->sc_fp);
1485     printf(" pc %08x\n", scp->sc_pc);
1486     printf(" opcode %04x\n", opcode);
1487     printf(" sr %08x\n", scp->sc_ps);
1488     printf(" state %p:\n", state);
1489     printf(" flags %d\n", state->ss_flags);
1490     for (int i=0; i<8; i++)
1491     printf(" d%d %08x\n", i, state->ss_frame.f_regs[i]);
1492     for (int i=0; i<8; i++)
1493     printf(" a%d %08x\n", i, state->ss_frame.f_regs[i+8]);
1494    
1495 cebix 1.37 VideoQuitFullScreen();
1496 cebix 1.12 #ifdef ENABLE_MON
1497 cebix 1.21 char *arg[4] = {"mon", "-m", "-r", NULL};
1498     mon(3, arg);
1499 cebix 1.12 #endif
1500     QuitEmulator();
1501     break;
1502 cebix 1.1 }
1503     }
1504 cebix 1.12 #endif
1505 cebix 1.1
1506    
1507     /*
1508     * Display alert
1509     */
1510    
1511 cebix 1.12 #ifdef ENABLE_GTK
1512 cebix 1.1 static void dl_destroyed(void)
1513     {
1514     gtk_main_quit();
1515     }
1516    
1517     static void dl_quit(GtkWidget *dialog)
1518     {
1519     gtk_widget_destroy(dialog);
1520     }
1521    
1522     void display_alert(int title_id, int prefix_id, int button_id, const char *text)
1523     {
1524     char str[256];
1525     sprintf(str, GetString(prefix_id), text);
1526    
1527     GtkWidget *dialog = gtk_dialog_new();
1528     gtk_window_set_title(GTK_WINDOW(dialog), GetString(title_id));
1529     gtk_container_border_width(GTK_CONTAINER(dialog), 5);
1530     gtk_widget_set_uposition(GTK_WIDGET(dialog), 100, 150);
1531     gtk_signal_connect(GTK_OBJECT(dialog), "destroy", GTK_SIGNAL_FUNC(dl_destroyed), NULL);
1532    
1533     GtkWidget *label = gtk_label_new(str);
1534     gtk_widget_show(label);
1535     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->vbox), label, TRUE, TRUE, 0);
1536    
1537     GtkWidget *button = gtk_button_new_with_label(GetString(button_id));
1538     gtk_widget_show(button);
1539     gtk_signal_connect_object(GTK_OBJECT(button), "clicked", GTK_SIGNAL_FUNC(dl_quit), GTK_OBJECT(dialog));
1540     gtk_box_pack_start(GTK_BOX(GTK_DIALOG(dialog)->action_area), button, FALSE, FALSE, 0);
1541     GTK_WIDGET_SET_FLAGS(button, GTK_CAN_DEFAULT);
1542     gtk_widget_grab_default(button);
1543     gtk_widget_show(dialog);
1544    
1545     gtk_main();
1546     }
1547     #endif
1548    
1549    
1550     /*
1551     * Display error alert
1552     */
1553    
1554     void ErrorAlert(const char *text)
1555     {
1556 gbeauche 1.74 if (gui_connection) {
1557     if (rpc_method_invoke(gui_connection, RPC_METHOD_ERROR_ALERT, RPC_TYPE_STRING, text, RPC_TYPE_INVALID) == RPC_ERROR_NO_ERROR &&
1558     rpc_method_wait_for_reply(gui_connection, RPC_TYPE_INVALID) == RPC_ERROR_NO_ERROR)
1559     return;
1560     }
1561 gbeauche 1.59 #if defined(ENABLE_GTK) && !defined(USE_SDL_VIDEO)
1562 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
1563     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1564     return;
1565     }
1566     VideoQuitFullScreen();
1567     display_alert(STR_ERROR_ALERT_TITLE, STR_GUI_ERROR_PREFIX, STR_QUIT_BUTTON, text);
1568     #else
1569     printf(GetString(STR_SHELL_ERROR_PREFIX), text);
1570     #endif
1571     }
1572    
1573    
1574     /*
1575     * Display warning alert
1576     */
1577    
1578     void WarningAlert(const char *text)
1579     {
1580 gbeauche 1.74 if (gui_connection) {
1581     if (rpc_method_invoke(gui_connection, RPC_METHOD_WARNING_ALERT, RPC_TYPE_STRING, text, RPC_TYPE_INVALID) == RPC_ERROR_NO_ERROR &&
1582     rpc_method_wait_for_reply(gui_connection, RPC_TYPE_INVALID) == RPC_ERROR_NO_ERROR)
1583     return;
1584     }
1585 gbeauche 1.59 #if defined(ENABLE_GTK) && !defined(USE_SDL_VIDEO)
1586 cebix 1.1 if (PrefsFindBool("nogui") || x_display == NULL) {
1587     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1588     return;
1589     }
1590     display_alert(STR_WARNING_ALERT_TITLE, STR_GUI_WARNING_PREFIX, STR_OK_BUTTON, text);
1591     #else
1592     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1593     #endif
1594     }
1595    
1596    
1597     /*
1598     * Display choice alert
1599     */
1600    
1601     bool ChoiceAlert(const char *text, const char *pos, const char *neg)
1602     {
1603     printf(GetString(STR_SHELL_WARNING_PREFIX), text);
1604     return false; //!!
1605     }