ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/sigsegv.cpp
(Generate patch)

Comparing BasiliskII/src/Unix/sigsegv.cpp (file contents):
Revision 1.3 by gbeauche, 2001-06-05T12:16:34Z vs.
Revision 1.32 by gbeauche, 2003-10-21T21:59:41Z

# Line 4 | Line 4
4   *  Derived from Bruno Haible's work on his SIGSEGV library for clisp
5   *  <http://clisp.sourceforge.net/>
6   *
7 < *  Basilisk II (C) 1997-2001 Christian Bauer
7 > *  MacOS X support derived from the post by Timothy J. Wood to the
8 > *  omnigroup macosx-dev list:
9 > *    Mach Exception Handlers 101 (Was Re: ptrace, gdb)
10 > *    tjw@omnigroup.com Sun, 4 Jun 2000
11 > *    www.omnigroup.com/mailman/archive/macosx-dev/2000-June/002030.html
12 > *
13 > *  Basilisk II (C) 1997-2002 Christian Bauer
14   *
15   *  This program is free software; you can redistribute it and/or modify
16   *  it under the terms of the GNU General Public License as published by
# Line 29 | Line 35
35   #include "config.h"
36   #endif
37  
38 + #include <list>
39   #include <signal.h>
40   #include "sigsegv.h"
41  
42 + #ifndef NO_STD_NAMESPACE
43 + using std::list;
44 + #endif
45 +
46   // Return value type of a signal handler (standard type if not defined)
47   #ifndef RETSIGTYPE
48   #define RETSIGTYPE void
# Line 41 | Line 52
52   typedef RETSIGTYPE (*signal_handler)(int);
53  
54   // User's SIGSEGV handler
55 < static sigsegv_handler_t sigsegv_user_handler = 0;
55 > static sigsegv_fault_handler_t sigsegv_fault_handler = 0;
56 >
57 > // Function called to dump state if we can't handle the fault
58 > static sigsegv_state_dumper_t sigsegv_state_dumper = 0;
59  
60   // Actual SIGSEGV handler installer
61   static bool sigsegv_do_install_handler(int sig);
62  
63  
64   /*
65 + *  Instruction decoding aids
66 + */
67 +
68 + // Transfer size
69 + enum transfer_size_t {
70 +        SIZE_UNKNOWN,
71 +        SIZE_BYTE,
72 +        SIZE_WORD,
73 +        SIZE_LONG
74 + };
75 +
76 + // Transfer type
77 + typedef sigsegv_transfer_type_t transfer_type_t;
78 +
79 + #if (defined(powerpc) || defined(__powerpc__) || defined(__ppc__))
80 + // Addressing mode
81 + enum addressing_mode_t {
82 +        MODE_UNKNOWN,
83 +        MODE_NORM,
84 +        MODE_U,
85 +        MODE_X,
86 +        MODE_UX
87 + };
88 +
89 + // Decoded instruction
90 + struct instruction_t {
91 +        transfer_type_t         transfer_type;
92 +        transfer_size_t         transfer_size;
93 +        addressing_mode_t       addr_mode;
94 +        unsigned int            addr;
95 +        char                            ra, rd;
96 + };
97 +
98 + static void powerpc_decode_instruction(instruction_t *instruction, unsigned int nip, unsigned int * gpr)
99 + {
100 +        // Get opcode and divide into fields
101 +        unsigned int opcode = *((unsigned int *)nip);
102 +        unsigned int primop = opcode >> 26;
103 +        unsigned int exop = (opcode >> 1) & 0x3ff;
104 +        unsigned int ra = (opcode >> 16) & 0x1f;
105 +        unsigned int rb = (opcode >> 11) & 0x1f;
106 +        unsigned int rd = (opcode >> 21) & 0x1f;
107 +        signed int imm = (signed short)(opcode & 0xffff);
108 +        
109 +        // Analyze opcode
110 +        transfer_type_t transfer_type = SIGSEGV_TRANSFER_UNKNOWN;
111 +        transfer_size_t transfer_size = SIZE_UNKNOWN;
112 +        addressing_mode_t addr_mode = MODE_UNKNOWN;
113 +        switch (primop) {
114 +        case 31:
115 +                switch (exop) {
116 +                case 23:        // lwzx
117 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_LONG; addr_mode = MODE_X; break;
118 +                case 55:        // lwzux
119 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_LONG; addr_mode = MODE_UX; break;
120 +                case 87:        // lbzx
121 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
122 +                case 119:       // lbzux
123 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
124 +                case 151:       // stwx
125 +                        transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_LONG; addr_mode = MODE_X; break;
126 +                case 183:       // stwux
127 +                        transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_LONG; addr_mode = MODE_UX; break;
128 +                case 215:       // stbx
129 +                        transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_X; break;
130 +                case 247:       // stbux
131 +                        transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_UX; break;
132 +                case 279:       // lhzx
133 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
134 +                case 311:       // lhzux
135 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
136 +                case 343:       // lhax
137 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
138 +                case 375:       // lhaux
139 +                        transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
140 +                case 407:       // sthx
141 +                        transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_X; break;
142 +                case 439:       // sthux
143 +                        transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_UX; break;
144 +                }
145 +                break;
146 +        
147 +        case 32:        // lwz
148 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_LONG; addr_mode = MODE_NORM; break;
149 +        case 33:        // lwzu
150 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_LONG; addr_mode = MODE_U; break;
151 +        case 34:        // lbz
152 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
153 +        case 35:        // lbzu
154 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
155 +        case 36:        // stw
156 +                transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_LONG; addr_mode = MODE_NORM; break;
157 +        case 37:        // stwu
158 +                transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_LONG; addr_mode = MODE_U; break;
159 +        case 38:        // stb
160 +                transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_NORM; break;
161 +        case 39:        // stbu
162 +                transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_BYTE; addr_mode = MODE_U; break;
163 +        case 40:        // lhz
164 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
165 +        case 41:        // lhzu
166 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
167 +        case 42:        // lha
168 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
169 +        case 43:        // lhau
170 +                transfer_type = SIGSEGV_TRANSFER_LOAD; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
171 +        case 44:        // sth
172 +                transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_NORM; break;
173 +        case 45:        // sthu
174 +                transfer_type = SIGSEGV_TRANSFER_STORE; transfer_size = SIZE_WORD; addr_mode = MODE_U; break;
175 +        }
176 +        
177 +        // Calculate effective address
178 +        unsigned int addr = 0;
179 +        switch (addr_mode) {
180 +        case MODE_X:
181 +        case MODE_UX:
182 +                if (ra == 0)
183 +                        addr = gpr[rb];
184 +                else
185 +                        addr = gpr[ra] + gpr[rb];
186 +                break;
187 +        case MODE_NORM:
188 +        case MODE_U:
189 +                if (ra == 0)
190 +                        addr = (signed int)(signed short)imm;
191 +                else
192 +                        addr = gpr[ra] + (signed int)(signed short)imm;
193 +                break;
194 +        default:
195 +                break;
196 +        }
197 +        
198 +        // Commit decoded instruction
199 +        instruction->addr = addr;
200 +        instruction->addr_mode = addr_mode;
201 +        instruction->transfer_type = transfer_type;
202 +        instruction->transfer_size = transfer_size;
203 +        instruction->ra = ra;
204 +        instruction->rd = rd;
205 + }
206 + #endif
207 +
208 +
209 + /*
210   *  OS-dependant SIGSEGV signals support section
211   */
212  
213   #if HAVE_SIGINFO_T
214   // Generic extended signal handler
215 + #if defined(__NetBSD__) || defined(__FreeBSD__)
216 + #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGBUS)
217 + #else
218   #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGSEGV)
219 < #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, siginfo_t *sip, void *
219 > #endif
220 > #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, siginfo_t *sip, void *scp
221 > #define SIGSEGV_FAULT_HANDLER_ARGLIST_1 siginfo_t *sip, void *scp
222 > #define SIGSEGV_FAULT_HANDLER_ARGS              sip, scp
223   #define SIGSEGV_FAULT_ADDRESS                   sip->si_addr
224 + #if defined(__sun__)
225 + #if (defined(sparc) || defined(__sparc__))
226 + #include <sys/ucontext.h>
227 + #define SIGSEGV_CONTEXT_REGS                    (((ucontext_t *)scp)->uc_mcontext.gregs)
228 + #define SIGSEGV_FAULT_INSTRUCTION               SIGSEGV_CONTEXT_REGS[REG_PC]
229 + #endif
230 + #endif
231 + #if defined(__NetBSD__) || defined(__FreeBSD__)
232 + #if (defined(i386) || defined(__i386__))
233 + #define SIGSEGV_FAULT_INSTRUCTION               (((struct sigcontext *)scp)->sc_eip)
234 + #define SIGSEGV_REGISTER_FILE                   ((unsigned int *)&(((struct sigcontext *)scp)->sc_edi)) /* EDI is the first GPR (even below EIP) in sigcontext */
235 + #define SIGSEGV_SKIP_INSTRUCTION                ix86_skip_instruction
236 + #endif
237 + #endif
238 + #if defined(__linux__)
239 + #if (defined(i386) || defined(__i386__))
240 + #include <sys/ucontext.h>
241 + #define SIGSEGV_CONTEXT_REGS                    (((ucontext_t *)scp)->uc_mcontext.gregs)
242 + #define SIGSEGV_FAULT_INSTRUCTION               SIGSEGV_CONTEXT_REGS[14] /* should use REG_EIP instead */
243 + #define SIGSEGV_REGISTER_FILE                   (unsigned int *)SIGSEGV_CONTEXT_REGS
244 + #define SIGSEGV_SKIP_INSTRUCTION                ix86_skip_instruction
245 + #endif
246 + #if (defined(x86_64) || defined(__x86_64__))
247 + #include <sys/ucontext.h>
248 + #define SIGSEGV_CONTEXT_REGS                    (((ucontext_t *)scp)->uc_mcontext.gregs)
249 + #define SIGSEGV_FAULT_INSTRUCTION               SIGSEGV_CONTEXT_REGS[16] /* should use REG_RIP instead */
250 + #define SIGSEGV_REGISTER_FILE                   (unsigned long *)SIGSEGV_CONTEXT_REGS
251 + #endif
252 + #if (defined(ia64) || defined(__ia64__))
253 + #define SIGSEGV_FAULT_INSTRUCTION               (((struct sigcontext *)scp)->sc_ip & ~0x3ULL) /* slot number is in bits 0 and 1 */
254 + #endif
255 + #if (defined(powerpc) || defined(__powerpc__))
256 + #include <sys/ucontext.h>
257 + #define SIGSEGV_CONTEXT_REGS                    (((ucontext_t *)scp)->uc_mcontext.regs)
258 + #define SIGSEGV_FAULT_INSTRUCTION               (SIGSEGV_CONTEXT_REGS->nip)
259 + #define SIGSEGV_REGISTER_FILE                   (unsigned int *)&SIGSEGV_CONTEXT_REGS->nip, (unsigned int *)(SIGSEGV_CONTEXT_REGS->gpr)
260 + #define SIGSEGV_SKIP_INSTRUCTION                powerpc_skip_instruction
261 + #endif
262 + #endif
263   #endif
264  
265   #if HAVE_SIGCONTEXT_SUBTERFUGE
# Line 65 | Line 269 | static bool sigsegv_do_install_handler(i
269   #if (defined(i386) || defined(__i386__))
270   #include <asm/sigcontext.h>
271   #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, struct sigcontext scs
272 < #define SIGSEGV_FAULT_ADDRESS                   scs.cr2
273 < #define SIGSEGV_FAULT_INSTRUCTION               scs.eip
272 > #define SIGSEGV_FAULT_HANDLER_ARGLIST_1 struct sigcontext *scp
273 > #define SIGSEGV_FAULT_HANDLER_ARGS              &scs
274 > #define SIGSEGV_FAULT_ADDRESS                   scp->cr2
275 > #define SIGSEGV_FAULT_INSTRUCTION               scp->eip
276 > #define SIGSEGV_REGISTER_FILE                   (unsigned int *)scp
277 > #define SIGSEGV_SKIP_INSTRUCTION                ix86_skip_instruction
278   #endif
279   #if (defined(sparc) || defined(__sparc__))
280   #include <asm/sigcontext.h>
281 < #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext* scp, char* addr
281 > #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp, char *addr
282 > #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp, addr
283   #define SIGSEGV_FAULT_ADDRESS                   addr
284   #endif
285   #if (defined(powerpc) || defined(__powerpc__))
286   #include <asm/sigcontext.h>
287 < #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, struct sigcontext* scp
287 > #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, struct sigcontext *scp
288 > #define SIGSEGV_FAULT_HANDLER_ARGS              sig, scp
289   #define SIGSEGV_FAULT_ADDRESS                   scp->regs->dar
290   #define SIGSEGV_FAULT_INSTRUCTION               scp->regs->nip
291 + #define SIGSEGV_REGISTER_FILE                   (unsigned int *)&scp->regs->nip, (unsigned int *)(scp->regs->gpr)
292 + #define SIGSEGV_SKIP_INSTRUCTION                powerpc_skip_instruction
293 + #endif
294 + #if (defined(alpha) || defined(__alpha__))
295 + #include <asm/sigcontext.h>
296 + #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp
297 + #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp
298 + #define SIGSEGV_FAULT_ADDRESS                   get_fault_address(scp)
299 + #define SIGSEGV_FAULT_INSTRUCTION               scp->sc_pc
300 +
301 + // From Boehm's GC 6.0alpha8
302 + static sigsegv_address_t get_fault_address(struct sigcontext *scp)
303 + {
304 +        unsigned int instruction = *((unsigned int *)(scp->sc_pc));
305 +        unsigned long fault_address = scp->sc_regs[(instruction >> 16) & 0x1f];
306 +        fault_address += (signed long)(signed short)(instruction & 0xffff);
307 +        return (sigsegv_address_t)fault_address;
308 + }
309   #endif
310   #endif
311  
312   // Irix 5 or 6 on MIPS
313   #if (defined(sgi) || defined(__sgi)) && (defined(SYSTYPE_SVR4) || defined(__SYSTYPE_SVR4))
314 + #include <ucontext.h>
315   #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp
316 + #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp
317   #define SIGSEGV_FAULT_ADDRESS                   scp->sc_badvaddr
318   #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGSEGV)
319   #endif
320  
321 + // HP-UX
322 + #if (defined(hpux) || defined(__hpux__))
323 + #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp
324 + #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp
325 + #define SIGSEGV_FAULT_ADDRESS                   scp->sc_sl.sl_ss.ss_narrow.ss_cr21
326 + #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGSEGV) FAULT_HANDLER(SIGBUS)
327 + #endif
328 +
329   // OSF/1 on Alpha
330   #if defined(__osf__)
331 + #include <ucontext.h>
332   #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp
333 + #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp
334   #define SIGSEGV_FAULT_ADDRESS                   scp->sc_traparg_a0
335   #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGSEGV)
336   #endif
# Line 98 | Line 338 | static bool sigsegv_do_install_handler(i
338   // AIX
339   #if defined(_AIX)
340   #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp
341 + #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp
342   #define SIGSEGV_FAULT_ADDRESS                   scp->sc_jmpbuf.jmp_context.o_vaddr
343   #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGSEGV)
344   #endif
# Line 107 | Line 348 | static bool sigsegv_do_install_handler(i
348   #if (defined(m68k) || defined(__m68k__))
349   #include <m68k/frame.h>
350   #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp
351 < #define SIGSEGV_FAULT_ADDRESS                   ({                                                                                                                              \
352 <        struct sigstate {                                                                                                                                                                       \
112 <                int ss_flags;                                                                                                                                                                   \
113 <                struct frame ss_frame;                                                                                                                                                  \
114 <        };                                                                                                                                                                                                      \
115 <        struct sigstate *state = (struct sigstate *)scp->sc_ap;                                                                                         \
116 <        char *fault_addr;                                                                                                                                                                       \
117 <        switch (state->ss_frame.f_format) {                                                                                                                                     \
118 <        case 7:         /* 68040 access error */                                                                                                                                \
119 <                /* "code" is sometimes unreliable (i.e. contains NULL or a bogus address), reason unknown */    \
120 <                fault_addr = state->ss_frame.f_fmt7.f_fa;                                                                                                               \
121 <                break;                                                                                                                                                                                  \
122 <        default:                                                                                                                                                                                        \
123 <                fault_addr = (char *)code;                                                                                                                                              \
124 <                break;                                                                                                                                                                                  \
125 <        }                                                                                                                                                                                                       \
126 <        fault_addr;                                                                                                                                                                                     \
127 < })
351 > #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp
352 > #define SIGSEGV_FAULT_ADDRESS                   get_fault_address(scp)
353   #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGSEGV)
354 +
355 + // Use decoding scheme from BasiliskII/m68k native
356 + static sigsegv_address_t get_fault_address(struct sigcontext *scp)
357 + {
358 +        struct sigstate {
359 +                int ss_flags;
360 +                struct frame ss_frame;
361 +        };
362 +        struct sigstate *state = (struct sigstate *)scp->sc_ap;
363 +        char *fault_addr;
364 +        switch (state->ss_frame.f_format) {
365 +        case 7:         /* 68040 access error */
366 +                /* "code" is sometimes unreliable (i.e. contains NULL or a bogus address), reason unknown */
367 +                fault_addr = state->ss_frame.f_fmt7.f_fa;
368 +                break;
369 +        default:
370 +                fault_addr = (char *)code;
371 +                break;
372 +        }
373 +        return (sigsegv_address_t)fault_addr;
374 + }
375   #else
376   #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, void *scp, char *addr
377 + #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp, addr
378   #define SIGSEGV_FAULT_ADDRESS                   addr
379   #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGBUS)
380   #endif
381   #endif
382 +
383 + // MacOS X, not sure which version this works in. Under 10.1
384 + // vm_protect does not appear to work from a signal handler. Under
385 + // 10.2 signal handlers get siginfo type arguments but the si_addr
386 + // field is the address of the faulting instruction and not the
387 + // address that caused the SIGBUS. Maybe this works in 10.0? In any
388 + // case with Mach exception handlers there is a way to do what this
389 + // was meant to do.
390 + #ifndef HAVE_MACH_EXCEPTIONS
391 + #if defined(__APPLE__) && defined(__MACH__)
392 + #if (defined(ppc) || defined(__ppc__))
393 + #define SIGSEGV_FAULT_HANDLER_ARGLIST   int sig, int code, struct sigcontext *scp
394 + #define SIGSEGV_FAULT_HANDLER_ARGS              sig, code, scp
395 + #define SIGSEGV_FAULT_ADDRESS                   get_fault_address(scp)
396 + #define SIGSEGV_FAULT_INSTRUCTION               scp->sc_ir
397 + #define SIGSEGV_ALL_SIGNALS                             FAULT_HANDLER(SIGBUS)
398 + #define SIGSEGV_REGISTER_FILE                   (unsigned int *)&scp->sc_ir, &((unsigned int *) scp->sc_regs)[2]
399 + #define SIGSEGV_SKIP_INSTRUCTION                powerpc_skip_instruction
400 +
401 + // Use decoding scheme from SheepShaver
402 + static sigsegv_address_t get_fault_address(struct sigcontext *scp)
403 + {
404 +        unsigned int   nip = (unsigned int) scp->sc_ir;
405 +        unsigned int * gpr = &((unsigned int *) scp->sc_regs)[2];
406 +        instruction_t  instr;
407 +
408 +        powerpc_decode_instruction(&instr, nip, gpr);
409 +        return (sigsegv_address_t)instr.addr;
410 + }
411 + #endif
412 + #endif
413 + #endif
414 + #endif
415 +
416 + #if HAVE_MACH_EXCEPTIONS
417 +
418 + // This can easily be extended to other Mach systems, but really who
419 + // uses HURD (oops GNU/HURD), Darwin/x86, NextStep, Rhapsody, or CMU
420 + // Mach 2.5/3.0?
421 + #if defined(__APPLE__) && defined(__MACH__)
422 +
423 + #include <sys/types.h>
424 + #include <stdlib.h>
425 + #include <stdio.h>
426 + #include <pthread.h>
427 +
428 + /*
429 + * If you are familiar with MIG then you will understand the frustration
430 + * that was necessary to get these embedded into C++ code by hand.
431 + */
432 + extern "C" {
433 + #include <mach/mach.h>
434 + #include <mach/mach_error.h>
435 +
436 + extern boolean_t exc_server(mach_msg_header_t *, mach_msg_header_t *);
437 + extern kern_return_t catch_exception_raise(mach_port_t, mach_port_t,
438 +        mach_port_t, exception_type_t, exception_data_t, mach_msg_type_number_t);
439 + extern kern_return_t exception_raise(mach_port_t, mach_port_t, mach_port_t,
440 +        exception_type_t, exception_data_t, mach_msg_type_number_t);
441 + extern kern_return_t exception_raise_state(mach_port_t, exception_type_t,
442 +        exception_data_t, mach_msg_type_number_t, thread_state_flavor_t *,
443 +        thread_state_t, mach_msg_type_number_t, thread_state_t, mach_msg_type_number_t *);
444 + extern kern_return_t exception_raise_state_identity(mach_port_t, mach_port_t, mach_port_t,
445 +        exception_type_t, exception_data_t, mach_msg_type_number_t, thread_state_flavor_t *,
446 +        thread_state_t, mach_msg_type_number_t, thread_state_t, mach_msg_type_number_t *);
447 + }
448 +
449 + // Could make this dynamic by looking for a result of MIG_ARRAY_TOO_LARGE
450 + #define HANDLER_COUNT 64
451 +
452 + // structure to tuck away existing exception handlers
453 + typedef struct _ExceptionPorts {
454 +        mach_msg_type_number_t maskCount;
455 +        exception_mask_t masks[HANDLER_COUNT];
456 +        exception_handler_t handlers[HANDLER_COUNT];
457 +        exception_behavior_t behaviors[HANDLER_COUNT];
458 +        thread_state_flavor_t flavors[HANDLER_COUNT];
459 + } ExceptionPorts;
460 +
461 + // exception handler thread
462 + static pthread_t exc_thread;
463 +
464 + // place where old exception handler info is stored
465 + static ExceptionPorts ports;
466 +
467 + // our exception port
468 + static mach_port_t _exceptionPort = MACH_PORT_NULL;
469 +
470 + #define MACH_CHECK_ERROR(name,ret) \
471 + if (ret != KERN_SUCCESS) { \
472 +        mach_error(#name, ret); \
473 +        exit (1); \
474 + }
475 +
476 + #define SIGSEGV_FAULT_ADDRESS                   code[1]
477 + #define SIGSEGV_FAULT_INSTRUCTION               get_fault_instruction(thread, state)
478 + #define SIGSEGV_FAULT_HANDLER_INVOKE(ADDR, IP)  ((code[0] == KERN_PROTECTION_FAILURE) ? sigsegv_fault_handler(ADDR, IP) : SIGSEGV_RETURN_FAILURE)
479 + #define SIGSEGV_FAULT_HANDLER_ARGLIST   mach_port_t thread, exception_data_t code, ppc_thread_state_t *state
480 + #define SIGSEGV_FAULT_HANDLER_ARGS              thread, code, &state
481 + #define SIGSEGV_SKIP_INSTRUCTION                powerpc_skip_instruction
482 + #define SIGSEGV_REGISTER_FILE                   &state->srr0, &state->r0
483 +
484 + // Given a suspended thread, stuff the current instruction and
485 + // registers into state.
486 + //
487 + // It would have been nice to have this be ppc/x86 independant which
488 + // could have been done easily with a thread_state_t instead of
489 + // ppc_thread_state_t, but because of the way this is called it is
490 + // easier to do it this way.
491 + #if (defined(ppc) || defined(__ppc__))
492 + static inline sigsegv_address_t get_fault_instruction(mach_port_t thread, ppc_thread_state_t *state)
493 + {
494 +        kern_return_t krc;
495 +        mach_msg_type_number_t count;
496 +
497 +        count = MACHINE_THREAD_STATE_COUNT;
498 +        krc = thread_get_state(thread, MACHINE_THREAD_STATE, (thread_state_t)state, &count);
499 +        MACH_CHECK_ERROR (thread_get_state, krc);
500 +
501 +        return (sigsegv_address_t)state->srr0;
502 + }
503 + #endif
504 +
505 + // Since there can only be one exception thread running at any time
506 + // this is not a problem.
507 + #define MSG_SIZE 512
508 + static char msgbuf[MSG_SIZE];
509 + static char replybuf[MSG_SIZE];
510 +
511 + /*
512 + * This is the entry point for the exception handler thread. The job
513 + * of this thread is to wait for exception messages on the exception
514 + * port that was setup beforehand and to pass them on to exc_server.
515 + * exc_server is a MIG generated function that is a part of Mach.
516 + * Its job is to decide what to do with the exception message. In our
517 + * case exc_server calls catch_exception_raise on our behalf. After
518 + * exc_server returns, it is our responsibility to send the reply.
519 + */
520 + static void *
521 + handleExceptions(void *priv)
522 + {
523 +        mach_msg_header_t *msg, *reply;
524 +        kern_return_t krc;
525 +
526 +        msg = (mach_msg_header_t *)msgbuf;
527 +        reply = (mach_msg_header_t *)replybuf;
528 +
529 +        for (;;) {
530 +                krc = mach_msg(msg, MACH_RCV_MSG, MSG_SIZE, MSG_SIZE,
531 +                                _exceptionPort, 0, MACH_PORT_NULL);
532 +                MACH_CHECK_ERROR(mach_msg, krc);
533 +
534 +                if (!exc_server(msg, reply)) {
535 +                        fprintf(stderr, "exc_server hated the message\n");
536 +                        exit(1);
537 +                }
538 +
539 +                krc = mach_msg(reply, MACH_SEND_MSG, reply->msgh_size, 0,
540 +                                 msg->msgh_local_port, 0, MACH_PORT_NULL);
541 +                if (krc != KERN_SUCCESS) {
542 +                        fprintf(stderr, "Error sending message to original reply port, krc = %d, %s",
543 +                                krc, mach_error_string(krc));
544 +                        exit(1);
545 +                }
546 +        }
547 + }
548 + #endif
549 + #endif
550 +
551 +
552 + /*
553 + *  Instruction skipping
554 + */
555 +
556 + #ifdef HAVE_SIGSEGV_SKIP_INSTRUCTION
557 + // Decode and skip X86 instruction
558 + #if (defined(i386) || defined(__i386__))
559 + #if defined(__linux__)
560 + enum {
561 +        X86_REG_EIP = 14,
562 +        X86_REG_EAX = 11,
563 +        X86_REG_ECX = 10,
564 +        X86_REG_EDX = 9,
565 +        X86_REG_EBX = 8,
566 +        X86_REG_ESP = 7,
567 +        X86_REG_EBP = 6,
568 +        X86_REG_ESI = 5,
569 +        X86_REG_EDI = 4
570 + };
571 + #endif
572 + #if defined(__NetBSD__) || defined(__FreeBSD__)
573 + enum {
574 +        X86_REG_EIP = 10,
575 +        X86_REG_EAX = 7,
576 +        X86_REG_ECX = 6,
577 +        X86_REG_EDX = 5,
578 +        X86_REG_EBX = 4,
579 +        X86_REG_ESP = 13,
580 +        X86_REG_EBP = 2,
581 +        X86_REG_ESI = 1,
582 +        X86_REG_EDI = 0
583 + };
584 + #endif
585 + // FIXME: this is partly redundant with the instruction decoding phase
586 + // to discover transfer type and register number
587 + static inline int ix86_step_over_modrm(unsigned char * p)
588 + {
589 +        int mod = (p[0] >> 6) & 3;
590 +        int rm = p[0] & 7;
591 +        int offset = 0;
592 +
593 +        // ModR/M Byte
594 +        switch (mod) {
595 +        case 0: // [reg]
596 +                if (rm == 5) return 4; // disp32
597 +                break;
598 +        case 1: // disp8[reg]
599 +                offset = 1;
600 +                break;
601 +        case 2: // disp32[reg]
602 +                offset = 4;
603 +                break;
604 +        case 3: // register
605 +                return 0;
606 +        }
607 +        
608 +        // SIB Byte
609 +        if (rm == 4) {
610 +                if (mod == 0 && (p[1] & 7) == 5)
611 +                        offset = 5; // disp32[index]
612 +                else
613 +                        offset++;
614 +        }
615 +
616 +        return offset;
617 + }
618 +
619 + static bool ix86_skip_instruction(unsigned int * regs)
620 + {
621 +        unsigned char * eip = (unsigned char *)regs[X86_REG_EIP];
622 +
623 +        if (eip == 0)
624 +                return false;
625 +        
626 +        transfer_type_t transfer_type = SIGSEGV_TRANSFER_UNKNOWN;
627 +        transfer_size_t transfer_size = SIZE_LONG;
628 +        
629 +        int reg = -1;
630 +        int len = 0;
631 +        
632 +        // Operand size prefix
633 +        if (*eip == 0x66) {
634 +                eip++;
635 +                len++;
636 +                transfer_size = SIZE_WORD;
637 +        }
638 +
639 +        // Decode instruction
640 +        switch (eip[0]) {
641 +        case 0x0f:
642 +            switch (eip[1]) {
643 +            case 0xb6: // MOVZX r32, r/m8
644 +            case 0xb7: // MOVZX r32, r/m16
645 +                switch (eip[2] & 0xc0) {
646 +                case 0x80:
647 +                    reg = (eip[2] >> 3) & 7;
648 +                    transfer_type = SIGSEGV_TRANSFER_LOAD;
649 +                    break;
650 +                case 0x40:
651 +                    reg = (eip[2] >> 3) & 7;
652 +                    transfer_type = SIGSEGV_TRANSFER_LOAD;
653 +                    break;
654 +                case 0x00:
655 +                    reg = (eip[2] >> 3) & 7;
656 +                    transfer_type = SIGSEGV_TRANSFER_LOAD;
657 +                    break;
658 +                }
659 +                len += 3 + ix86_step_over_modrm(eip + 2);
660 +                break;
661 +            }
662 +          break;
663 +        case 0x8a: // MOV r8, r/m8
664 +                transfer_size = SIZE_BYTE;
665 +        case 0x8b: // MOV r32, r/m32 (or 16-bit operation)
666 +                switch (eip[1] & 0xc0) {
667 +                case 0x80:
668 +                        reg = (eip[1] >> 3) & 7;
669 +                        transfer_type = SIGSEGV_TRANSFER_LOAD;
670 +                        break;
671 +                case 0x40:
672 +                        reg = (eip[1] >> 3) & 7;
673 +                        transfer_type = SIGSEGV_TRANSFER_LOAD;
674 +                        break;
675 +                case 0x00:
676 +                        reg = (eip[1] >> 3) & 7;
677 +                        transfer_type = SIGSEGV_TRANSFER_LOAD;
678 +                        break;
679 +                }
680 +                len += 2 + ix86_step_over_modrm(eip + 1);
681 +                break;
682 +        case 0x88: // MOV r/m8, r8
683 +                transfer_size = SIZE_BYTE;
684 +        case 0x89: // MOV r/m32, r32 (or 16-bit operation)
685 +                switch (eip[1] & 0xc0) {
686 +                case 0x80:
687 +                        reg = (eip[1] >> 3) & 7;
688 +                        transfer_type = SIGSEGV_TRANSFER_STORE;
689 +                        break;
690 +                case 0x40:
691 +                        reg = (eip[1] >> 3) & 7;
692 +                        transfer_type = SIGSEGV_TRANSFER_STORE;
693 +                        break;
694 +                case 0x00:
695 +                        reg = (eip[1] >> 3) & 7;
696 +                        transfer_type = SIGSEGV_TRANSFER_STORE;
697 +                        break;
698 +                }
699 +                len += 2 + ix86_step_over_modrm(eip + 1);
700 +                break;
701 +        }
702 +
703 +        if (transfer_type == SIGSEGV_TRANSFER_UNKNOWN) {
704 +                // Unknown machine code, let it crash. Then patch the decoder
705 +                return false;
706 +        }
707 +
708 +        if (transfer_type == SIGSEGV_TRANSFER_LOAD && reg != -1) {
709 +                static const int x86_reg_map[8] = {
710 +                        X86_REG_EAX, X86_REG_ECX, X86_REG_EDX, X86_REG_EBX,
711 +                        X86_REG_ESP, X86_REG_EBP, X86_REG_ESI, X86_REG_EDI
712 +                };
713 +                
714 +                if (reg < 0 || reg >= 8)
715 +                        return false;
716 +
717 +                int rloc = x86_reg_map[reg];
718 +                switch (transfer_size) {
719 +                case SIZE_BYTE:
720 +                        regs[rloc] = (regs[rloc] & ~0xff);
721 +                        break;
722 +                case SIZE_WORD:
723 +                        regs[rloc] = (regs[rloc] & ~0xffff);
724 +                        break;
725 +                case SIZE_LONG:
726 +                        regs[rloc] = 0;
727 +                        break;
728 +                }
729 +        }
730 +
731 + #if DEBUG
732 +        printf("%08x: %s %s access", regs[X86_REG_EIP],
733 +                   transfer_size == SIZE_BYTE ? "byte" : transfer_size == SIZE_WORD ? "word" : "long",
734 +                   transfer_type == SIGSEGV_TRANSFER_LOAD ? "read" : "write");
735 +        
736 +        if (reg != -1) {
737 +                static const char * x86_reg_str_map[8] = {
738 +                        "eax", "ecx", "edx", "ebx",
739 +                        "esp", "ebp", "esi", "edi"
740 +                };
741 +                printf(" %s register %%%s", transfer_type == SIGSEGV_TRANSFER_LOAD ? "to" : "from", x86_reg_str_map[reg]);
742 +        }
743 +        printf(", %d bytes instruction\n", len);
744 + #endif
745 +        
746 +        regs[X86_REG_EIP] += len;
747 +        return true;
748 + }
749 + #endif
750 +
751 + // Decode and skip PPC instruction
752 + #if (defined(powerpc) || defined(__powerpc__) || defined(__ppc__))
753 + static bool powerpc_skip_instruction(unsigned int * nip_p, unsigned int * regs)
754 + {
755 +        instruction_t instr;
756 +        powerpc_decode_instruction(&instr, *nip_p, regs);
757 +        
758 +        if (instr.transfer_type == SIGSEGV_TRANSFER_UNKNOWN) {
759 +                // Unknown machine code, let it crash. Then patch the decoder
760 +                return false;
761 +        }
762 +
763 + #if DEBUG
764 +        printf("%08x: %s %s access", *nip_p,
765 +                   instr.transfer_size == SIZE_BYTE ? "byte" : instr.transfer_size == SIZE_WORD ? "word" : "long",
766 +                   instr.transfer_type == SIGSEGV_TRANSFER_LOAD ? "read" : "write");
767 +        
768 +        if (instr.addr_mode == MODE_U || instr.addr_mode == MODE_UX)
769 +                printf(" r%d (ra = %08x)\n", instr.ra, instr.addr);
770 +        if (instr.transfer_type == SIGSEGV_TRANSFER_LOAD)
771 +                printf(" r%d (rd = 0)\n", instr.rd);
772 + #endif
773 +        
774 +        if (instr.addr_mode == MODE_U || instr.addr_mode == MODE_UX)
775 +                regs[instr.ra] = instr.addr;
776 +        if (instr.transfer_type == SIGSEGV_TRANSFER_LOAD)
777 +                regs[instr.rd] = 0;
778 +        
779 +        *nip_p += 4;
780 +        return true;
781 + }
782 + #endif
783   #endif
784  
785   // Fallbacks
786   #ifndef SIGSEGV_FAULT_INSTRUCTION
787   #define SIGSEGV_FAULT_INSTRUCTION               SIGSEGV_INVALID_PC
788   #endif
789 + #ifndef SIGSEGV_FAULT_HANDLER_ARGLIST_1
790 + #define SIGSEGV_FAULT_HANDLER_ARGLIST_1 SIGSEGV_FAULT_HANDLER_ARGLIST
791 + #endif
792 + #ifndef SIGSEGV_FAULT_HANDLER_INVOKE
793 + #define SIGSEGV_FAULT_HANDLER_INVOKE(ADDR, IP)  sigsegv_fault_handler(ADDR, IP)
794 + #endif
795  
796   // SIGSEGV recovery supported ?
797   #if defined(SIGSEGV_ALL_SIGNALS) && defined(SIGSEGV_FAULT_HANDLER_ARGLIST) && defined(SIGSEGV_FAULT_ADDRESS)
# Line 149 | Line 803 | static bool sigsegv_do_install_handler(i
803   *  SIGSEGV global handler
804   */
805  
806 + #if defined(HAVE_SIGSEGV_RECOVERY) || defined(HAVE_MACH_EXCEPTIONS)
807 + // This function handles the badaccess to memory.
808 + // It is called from the signal handler or the exception handler.
809 + static bool handle_badaccess(SIGSEGV_FAULT_HANDLER_ARGLIST_1)
810 + {
811 +        sigsegv_address_t fault_address = (sigsegv_address_t)SIGSEGV_FAULT_ADDRESS;
812 +        sigsegv_address_t fault_instruction = (sigsegv_address_t)SIGSEGV_FAULT_INSTRUCTION;
813 +        
814 +        // Call user's handler and reinstall the global handler, if required
815 +        switch (SIGSEGV_FAULT_HANDLER_INVOKE(fault_address, fault_instruction)) {
816 +        case SIGSEGV_RETURN_SUCCESS:
817 +                return true;
818 +
819 + #if HAVE_SIGSEGV_SKIP_INSTRUCTION
820 +        case SIGSEGV_RETURN_SKIP_INSTRUCTION:
821 +                // Call the instruction skipper with the register file
822 +                // available
823 +                if (SIGSEGV_SKIP_INSTRUCTION(SIGSEGV_REGISTER_FILE)) {
824 + #ifdef HAVE_MACH_EXCEPTIONS
825 +                        // Unlike UNIX signals where the thread state
826 +                        // is modified off of the stack, in Mach we
827 +                        // need to actually call thread_set_state to
828 +                        // have the register values updated.
829 +                        kern_return_t krc;
830 +
831 +                        krc = thread_set_state(thread,
832 +                                                                   MACHINE_THREAD_STATE, (thread_state_t)state,
833 +                                                                   MACHINE_THREAD_STATE_COUNT);
834 +                        MACH_CHECK_ERROR (thread_get_state, krc);
835 + #endif
836 +                        return true;
837 +                }
838 +                break;
839 + #endif
840 +        }
841 +        
842 +        // We can't do anything with the fault_address, dump state?
843 +        if (sigsegv_state_dumper != 0)
844 +                sigsegv_state_dumper(fault_address, fault_instruction);
845 +
846 +        return false;
847 + }
848 + #endif
849 +
850 +
851 + /*
852 + * There are two mechanisms for handling a bad memory access,
853 + * Mach exceptions and UNIX signals. The implementation specific
854 + * code appears below. Its reponsibility is to call handle_badaccess
855 + * which is the routine that handles the fault in an implementation
856 + * agnostic manner. The implementation specific code below is then
857 + * reponsible for checking whether handle_badaccess was able
858 + * to handle the memory access error and perform any implementation
859 + * specific tasks necessary afterwards.
860 + */
861 +
862 + #ifdef HAVE_MACH_EXCEPTIONS
863 + /*
864 + * We need to forward all exceptions that we do not handle.
865 + * This is important, there are many exceptions that may be
866 + * handled by other exception handlers. For example debuggers
867 + * use exceptions and the exception hander is in another
868 + * process in such a case. (Timothy J. Wood states in his
869 + * message to the list that he based this code on that from
870 + * gdb for Darwin.)
871 + */
872 + static inline kern_return_t
873 + forward_exception(mach_port_t thread_port,
874 +                                  mach_port_t task_port,
875 +                                  exception_type_t exception_type,
876 +                                  exception_data_t exception_data,
877 +                                  mach_msg_type_number_t data_count,
878 +                                  ExceptionPorts *oldExceptionPorts)
879 + {
880 +        kern_return_t kret;
881 +        unsigned int portIndex;
882 +        mach_port_t port;
883 +        exception_behavior_t behavior;
884 +        thread_state_flavor_t flavor;
885 +        thread_state_t thread_state;
886 +        mach_msg_type_number_t thread_state_count;
887 +
888 +        for (portIndex = 0; portIndex < oldExceptionPorts->maskCount; portIndex++) {
889 +                if (oldExceptionPorts->masks[portIndex] & (1 << exception_type)) {
890 +                        // This handler wants the exception
891 +                        break;
892 +                }
893 +        }
894 +
895 +        if (portIndex >= oldExceptionPorts->maskCount) {
896 +                fprintf(stderr, "No handler for exception_type = %d. Not fowarding\n", exception_type);
897 +                return KERN_FAILURE;
898 +        }
899 +
900 +        port = oldExceptionPorts->handlers[portIndex];
901 +        behavior = oldExceptionPorts->behaviors[portIndex];
902 +        flavor = oldExceptionPorts->flavors[portIndex];
903 +
904 +        /*
905 +         fprintf(stderr, "forwarding exception, port = 0x%x, behaviour = %d, flavor = %d\n", port, behavior, flavor);
906 +         */
907 +
908 +        if (behavior != EXCEPTION_DEFAULT) {
909 +                thread_state_count = THREAD_STATE_MAX;
910 +                kret = thread_get_state (thread_port, flavor, thread_state,
911 +                                                                 &thread_state_count);
912 +                MACH_CHECK_ERROR (thread_get_state, kret);
913 +        }
914 +
915 +        switch (behavior) {
916 +        case EXCEPTION_DEFAULT:
917 +          // fprintf(stderr, "forwarding to exception_raise\n");
918 +          kret = exception_raise(port, thread_port, task_port, exception_type,
919 +                                                         exception_data, data_count);
920 +          MACH_CHECK_ERROR (exception_raise, kret);
921 +          break;
922 +        case EXCEPTION_STATE:
923 +          // fprintf(stderr, "forwarding to exception_raise_state\n");
924 +          kret = exception_raise_state(port, exception_type, exception_data,
925 +                                                                   data_count, &flavor,
926 +                                                                   thread_state, thread_state_count,
927 +                                                                   thread_state, &thread_state_count);
928 +          MACH_CHECK_ERROR (exception_raise_state, kret);
929 +          break;
930 +        case EXCEPTION_STATE_IDENTITY:
931 +          // fprintf(stderr, "forwarding to exception_raise_state_identity\n");
932 +          kret = exception_raise_state_identity(port, thread_port, task_port,
933 +                                                                                        exception_type, exception_data,
934 +                                                                                        data_count, &flavor,
935 +                                                                                        thread_state, thread_state_count,
936 +                                                                                        thread_state, &thread_state_count);
937 +          MACH_CHECK_ERROR (exception_raise_state_identity, kret);
938 +          break;
939 +        default:
940 +          fprintf(stderr, "forward_exception got unknown behavior\n");
941 +          break;
942 +        }
943 +
944 +        if (behavior != EXCEPTION_DEFAULT) {
945 +                kret = thread_set_state (thread_port, flavor, thread_state,
946 +                                                                 thread_state_count);
947 +                MACH_CHECK_ERROR (thread_set_state, kret);
948 +        }
949 +
950 +        return KERN_SUCCESS;
951 + }
952 +
953 + /*
954 + * This is the code that actually handles the exception.
955 + * It is called by exc_server. For Darwin 5 Apple changed
956 + * this a bit from how this family of functions worked in
957 + * Mach. If you are familiar with that it is a little
958 + * different. The main variation that concerns us here is
959 + * that code is an array of exception specific codes and
960 + * codeCount is a count of the number of codes in the code
961 + * array. In typical Mach all exceptions have a code
962 + * and sub-code. It happens to be the case that for a
963 + * EXC_BAD_ACCESS exception the first entry is the type of
964 + * bad access that occurred and the second entry is the
965 + * faulting address so these entries correspond exactly to
966 + * how the code and sub-code are used on Mach.
967 + *
968 + * This is a MIG interface. No code in Basilisk II should
969 + * call this directley. This has to have external C
970 + * linkage because that is what exc_server expects.
971 + */
972 + kern_return_t
973 + catch_exception_raise(mach_port_t exception_port,
974 +                                          mach_port_t thread,
975 +                                          mach_port_t task,
976 +                                          exception_type_t exception,
977 +                                          exception_data_t code,
978 +                                          mach_msg_type_number_t codeCount)
979 + {
980 +        ppc_thread_state_t state;
981 +        kern_return_t krc;
982 +
983 +        if ((exception == EXC_BAD_ACCESS)  && (codeCount >= 2)) {
984 +                if (handle_badaccess(SIGSEGV_FAULT_HANDLER_ARGS))
985 +                        return KERN_SUCCESS;
986 +        }
987 +
988 +        // In Mach we do not need to remove the exception handler.
989 +        // If we forward the exception, eventually some exception handler
990 +        // will take care of this exception.
991 +        krc = forward_exception(thread, task, exception, code, codeCount, &ports);
992 +
993 +        return krc;
994 + }
995 + #endif
996 +
997   #ifdef HAVE_SIGSEGV_RECOVERY
998 + // Handle bad memory accesses with signal handler
999   static void sigsegv_handler(SIGSEGV_FAULT_HANDLER_ARGLIST)
1000   {
1001 <        // Call user's handler and reinstall the global handler, if required
1002 <        if (sigsegv_user_handler((sigsegv_address_t)SIGSEGV_FAULT_ADDRESS, (sigsegv_address_t)SIGSEGV_FAULT_INSTRUCTION)) {
1001 >        // Call handler and reinstall the global handler, if required
1002 >        if (handle_badaccess(SIGSEGV_FAULT_HANDLER_ARGS)) {
1003   #if (defined(HAVE_SIGACTION) ? defined(SIGACTION_NEED_REINSTALL) : defined(SIGNAL_NEED_REINSTALL))
1004                  sigsegv_do_install_handler(sig);
1005   #endif
1006 +                return;
1007          }
1008 <        else {
1009 <                // FAIL: reinstall default handler for "safe" crash
1008 >
1009 >        // Failure: reinstall default handler for "safe" crash
1010   #define FAULT_HANDLER(sig) signal(sig, SIG_DFL);
1011 <                SIGSEGV_ALL_SIGNALS
1011 >        SIGSEGV_ALL_SIGNALS
1012   #undef FAULT_HANDLER
166        }
1013   }
1014   #endif
1015  
# Line 177 | Line 1023 | static bool sigsegv_do_install_handler(i
1023   {
1024          // Setup SIGSEGV handler to process writes to frame buffer
1025   #ifdef HAVE_SIGACTION
1026 <        struct sigaction vosf_sa;
1027 <        sigemptyset(&vosf_sa.sa_mask);
1028 <        vosf_sa.sa_sigaction = sigsegv_handler;
1029 <        vosf_sa.sa_flags = SA_SIGINFO;
1030 <        return (sigaction(sig, &vosf_sa, 0) == 0);
1026 >        struct sigaction sigsegv_sa;
1027 >        sigemptyset(&sigsegv_sa.sa_mask);
1028 >        sigsegv_sa.sa_sigaction = sigsegv_handler;
1029 >        sigsegv_sa.sa_flags = SA_SIGINFO;
1030 >        return (sigaction(sig, &sigsegv_sa, 0) == 0);
1031   #else
1032          return (signal(sig, (signal_handler)sigsegv_handler) != SIG_ERR);
1033   #endif
# Line 193 | Line 1039 | static bool sigsegv_do_install_handler(i
1039   {
1040          // Setup SIGSEGV handler to process writes to frame buffer
1041   #ifdef HAVE_SIGACTION
1042 <        struct sigaction vosf_sa;
1043 <        sigemptyset(&vosf_sa.sa_mask);
1044 <        vosf_sa.sa_handler = (signal_handler)sigsegv_handler;
1042 >        struct sigaction sigsegv_sa;
1043 >        sigemptyset(&sigsegv_sa.sa_mask);
1044 >        sigsegv_sa.sa_handler = (signal_handler)sigsegv_handler;
1045 >        sigsegv_sa.sa_flags = 0;
1046   #if !EMULATED_68K && defined(__NetBSD__)
1047 <        sigaddset(&vosf_sa.sa_mask, SIGALRM);
1048 <        vosf_sa.sa_flags = SA_ONSTACK;
202 < #else
203 <        vosf_sa.sa_flags = 0;
1047 >        sigaddset(&sigsegv_sa.sa_mask, SIGALRM);
1048 >        sigsegv_sa.sa_flags |= SA_ONSTACK;
1049   #endif
1050 <        return (sigaction(sig, &vosf_sa, 0) == 0);
1050 >        return (sigaction(sig, &sigsegv_sa, 0) == 0);
1051   #else
1052          return (signal(sig, (signal_handler)sigsegv_handler) != SIG_ERR);
1053   #endif
1054   }
1055   #endif
1056  
1057 < bool sigsegv_install_handler(sigsegv_handler_t handler)
1057 > #if defined(HAVE_MACH_EXCEPTIONS)
1058 > static bool sigsegv_do_install_handler(sigsegv_fault_handler_t handler)
1059   {
1060 < #ifdef HAVE_SIGSEGV_RECOVERY
1061 <        sigsegv_user_handler = handler;
1060 >        /*
1061 >         * Except for the exception port functions, this should be
1062 >         * pretty much stock Mach. If later you choose to support
1063 >         * other Mach's besides Darwin, just check for __MACH__
1064 >         * here and __APPLE__ where the actual differences are.
1065 >         */
1066 > #if defined(__APPLE__) && defined(__MACH__)
1067 >        if (sigsegv_fault_handler != NULL) {
1068 >                sigsegv_fault_handler = handler;
1069 >                return true;
1070 >        }
1071 >
1072 >        kern_return_t krc;
1073 >
1074 >        // create the the exception port
1075 >        krc = mach_port_allocate(mach_task_self(),
1076 >                          MACH_PORT_RIGHT_RECEIVE, &_exceptionPort);
1077 >        if (krc != KERN_SUCCESS) {
1078 >                mach_error("mach_port_allocate", krc);
1079 >                return false;
1080 >        }
1081 >
1082 >        // add a port send right
1083 >        krc = mach_port_insert_right(mach_task_self(),
1084 >                              _exceptionPort, _exceptionPort,
1085 >                              MACH_MSG_TYPE_MAKE_SEND);
1086 >        if (krc != KERN_SUCCESS) {
1087 >                mach_error("mach_port_insert_right", krc);
1088 >                return false;
1089 >        }
1090 >
1091 >        // get the old exception ports
1092 >        ports.maskCount = sizeof (ports.masks) / sizeof (ports.masks[0]);
1093 >        krc = thread_get_exception_ports(mach_thread_self(), EXC_MASK_BAD_ACCESS, ports.masks,
1094 >                                &ports.maskCount, ports.handlers, ports.behaviors, ports.flavors);
1095 >        if (krc != KERN_SUCCESS) {
1096 >                mach_error("thread_get_exception_ports", krc);
1097 >                return false;
1098 >        }
1099 >
1100 >        // set the new exception port
1101 >        //
1102 >        // We could have used EXCEPTION_STATE_IDENTITY instead of
1103 >        // EXCEPTION_DEFAULT to get the thread state in the initial
1104 >        // message, but it turns out that in the common case this is not
1105 >        // neccessary. If we need it we can later ask for it from the
1106 >        // suspended thread.
1107 >        //
1108 >        // Even with THREAD_STATE_NONE, Darwin provides the program
1109 >        // counter in the thread state.  The comments in the header file
1110 >        // seem to imply that you can count on the GPR's on an exception
1111 >        // as well but just to be safe I use MACHINE_THREAD_STATE because
1112 >        // you have to ask for all of the GPR's anyway just to get the
1113 >        // program counter. In any case because of update effective
1114 >        // address from immediate and update address from effective
1115 >        // addresses of ra and rb modes (as good an name as any for these
1116 >        // addressing modes) used in PPC instructions, you will need the
1117 >        // GPR state anyway.
1118 >        krc = thread_set_exception_ports(mach_thread_self(), EXC_MASK_BAD_ACCESS, _exceptionPort,
1119 >                                EXCEPTION_DEFAULT, MACHINE_THREAD_STATE);
1120 >        if (krc != KERN_SUCCESS) {
1121 >                mach_error("thread_set_exception_ports", krc);
1122 >                return false;
1123 >        }
1124 >
1125 >        // create the exception handler thread
1126 >        if (pthread_create(&exc_thread, NULL, &handleExceptions, NULL) != 0) {
1127 >                (void)fprintf(stderr, "creation of exception thread failed\n");
1128 >                return false;
1129 >        }
1130 >
1131 >        // do not care about the exception thread any longer, let is run standalone
1132 >        (void)pthread_detach(exc_thread);
1133 >
1134 >        sigsegv_fault_handler = handler;
1135 >        return true;
1136 > #else
1137 >        return false;
1138 > #endif
1139 > }
1140 > #endif
1141 >
1142 > bool sigsegv_install_handler(sigsegv_fault_handler_t handler)
1143 > {
1144 > #if defined(HAVE_SIGSEGV_RECOVERY)
1145          bool success = true;
1146   #define FAULT_HANDLER(sig) success = success && sigsegv_do_install_handler(sig);
1147          SIGSEGV_ALL_SIGNALS
1148   #undef FAULT_HANDLER
1149 +        if (success)
1150 +            sigsegv_fault_handler = handler;
1151          return success;
1152 + #elif defined(HAVE_MACH_EXCEPTIONS)
1153 +        return sigsegv_do_install_handler(handler);
1154   #else
1155          // FAIL: no siginfo_t nor sigcontext subterfuge is available
1156          return false;
# Line 231 | Line 1164 | bool sigsegv_install_handler(sigsegv_han
1164  
1165   void sigsegv_deinstall_handler(void)
1166   {
1167 +  // We do nothing for Mach exceptions, the thread would need to be
1168 +  // suspended if not already so, and we might mess with other
1169 +  // exception handlers that came after we registered ours. There is
1170 +  // no need to remove the exception handler, in fact this function is
1171 +  // not called anywhere in Basilisk II.
1172   #ifdef HAVE_SIGSEGV_RECOVERY
1173 <        sigsegv_user_handler = 0;
1173 >        sigsegv_fault_handler = 0;
1174   #define FAULT_HANDLER(sig) signal(sig, SIG_DFL);
1175          SIGSEGV_ALL_SIGNALS
1176   #undef FAULT_HANDLER
1177   #endif
1178   }
1179  
1180 +
1181 + /*
1182 + *  Set callback function when we cannot handle the fault
1183 + */
1184 +
1185 + void sigsegv_set_dump_state(sigsegv_state_dumper_t handler)
1186 + {
1187 +        sigsegv_state_dumper = handler;
1188 + }
1189 +
1190 +
1191   /*
1192   *  Test program used for configure/test
1193   */
1194  
1195 < #ifdef CONFIGURE_TEST
1195 > #ifdef CONFIGURE_TEST_SIGSEGV_RECOVERY
1196   #include <stdio.h>
1197   #include <stdlib.h>
249 #include <unistd.h>
1198   #include <fcntl.h>
1199   #include <sys/mman.h>
1200 + #include "vm_alloc.h"
1201 +
1202 + const int REF_INDEX = 123;
1203 + const int REF_VALUE = 45;
1204  
1205   static int page_size;
1206   static volatile char * page = 0;
1207   static volatile int handler_called = 0;
1208  
1209 < static bool sigsegv_test_handler(sigsegv_address_t fault_address, sigsegv_address_t instruction_address)
1209 > #ifdef __GNUC__
1210 > // Code range where we expect the fault to come from
1211 > static void *b_region, *e_region;
1212 > #endif
1213 >
1214 > static sigsegv_return_t sigsegv_test_handler(sigsegv_address_t fault_address, sigsegv_address_t instruction_address)
1215   {
1216          handler_called++;
1217 <        if ((fault_address - 123) != page)
1218 <                exit(1);
1219 <        if (mprotect((char *)((unsigned long)fault_address & -page_size), page_size, PROT_READ | PROT_WRITE) != 0)
1220 <                exit(1);
1221 <        return true;
1217 >        if ((fault_address - REF_INDEX) != page)
1218 >                exit(10);
1219 > #ifdef __GNUC__
1220 >        // Make sure reported fault instruction address falls into
1221 >        // expected code range
1222 >        if (instruction_address != SIGSEGV_INVALID_PC
1223 >                && ((instruction_address <  (sigsegv_address_t)b_region) ||
1224 >                        (instruction_address >= (sigsegv_address_t)e_region)))
1225 >                exit(11);
1226 > #endif
1227 >        if (vm_protect((char *)((unsigned long)fault_address & -page_size), page_size, VM_PAGE_READ | VM_PAGE_WRITE) != 0)
1228 >                exit(12);
1229 >        return SIGSEGV_RETURN_SUCCESS;
1230   }
1231  
1232 + #ifdef HAVE_SIGSEGV_SKIP_INSTRUCTION
1233 + static sigsegv_return_t sigsegv_insn_handler(sigsegv_address_t fault_address, sigsegv_address_t instruction_address)
1234 + {
1235 +        if (((unsigned long)fault_address - (unsigned long)page) < page_size) {
1236 + #ifdef __GNUC__
1237 +                // Make sure reported fault instruction address falls into
1238 +                // expected code range
1239 +                if (instruction_address != SIGSEGV_INVALID_PC
1240 +                        && ((instruction_address <  (sigsegv_address_t)b_region) ||
1241 +                                (instruction_address >= (sigsegv_address_t)e_region)))
1242 +                        return SIGSEGV_RETURN_FAILURE;
1243 + #endif
1244 +                return SIGSEGV_RETURN_SKIP_INSTRUCTION;
1245 +        }
1246 +
1247 +        return SIGSEGV_RETURN_FAILURE;
1248 + }
1249 + #endif
1250 +
1251   int main(void)
1252   {
1253 <        int zero_fd = open("/dev/zero", O_RDWR);
270 <        if (zero_fd < 0)
1253 >        if (vm_init() < 0)
1254                  return 1;
1255  
1256          page_size = getpagesize();
1257 <        page = (char *)mmap(0, page_size, PROT_READ, MAP_PRIVATE, zero_fd, 0);
1258 <        if (page == MAP_FAILED)
276 <                return 1;
1257 >        if ((page = (char *)vm_acquire(page_size)) == VM_MAP_FAILED)
1258 >                return 2;
1259          
1260 <        if (!sigsegv_install_handler(sigsegv_test_handler))
1261 <                return 1;
1260 >        memset((void *)page, 0, page_size);
1261 >        if (vm_protect((char *)page, page_size, VM_PAGE_READ) < 0)
1262 >                return 3;
1263          
1264 <        page[123] = 45;
1265 <        page[123] = 45;
1264 >        if (!sigsegv_install_handler(sigsegv_test_handler))
1265 >                return 4;
1266          
1267 + #ifdef __GNUC__
1268 +        b_region = &&L_b_region1;
1269 +        e_region = &&L_e_region1;
1270 + #endif
1271 + L_b_region1:
1272 +        page[REF_INDEX] = REF_VALUE;
1273 +        if (page[REF_INDEX] != REF_VALUE)
1274 +          exit(20);
1275 +        page[REF_INDEX] = REF_VALUE;
1276 + L_e_region1:
1277 +
1278          if (handler_called != 1)
1279 <                return 1;
1279 >                return 5;
1280 >
1281 > #ifdef HAVE_SIGSEGV_SKIP_INSTRUCTION
1282 >        if (!sigsegv_install_handler(sigsegv_insn_handler))
1283 >                return 6;
1284 >        
1285 >        if (vm_protect((char *)page, page_size, VM_PAGE_READ | VM_PAGE_WRITE) < 0)
1286 >                return 7;
1287 >        
1288 >        for (int i = 0; i < page_size; i++)
1289 >                page[i] = (i + 1) % page_size;
1290 >        
1291 >        if (vm_protect((char *)page, page_size, VM_PAGE_NOACCESS) < 0)
1292 >                return 8;
1293 >        
1294 > #define TEST_SKIP_INSTRUCTION(TYPE) do {                                \
1295 >                const unsigned int TAG = 0x12345678;                    \
1296 >                TYPE data = *((TYPE *)(page + sizeof(TYPE)));   \
1297 >                volatile unsigned int effect = data + TAG;              \
1298 >                if (effect != TAG)                                                              \
1299 >                        return 9;                                                                       \
1300 >        } while (0)
1301 >        
1302 > #ifdef __GNUC__
1303 >        b_region = &&L_b_region2;
1304 >        e_region = &&L_e_region2;
1305 > #endif
1306 > L_b_region2:
1307 >        TEST_SKIP_INSTRUCTION(unsigned char);
1308 >        TEST_SKIP_INSTRUCTION(unsigned short);
1309 >        TEST_SKIP_INSTRUCTION(unsigned int);
1310 > L_e_region2:
1311 > #endif
1312  
1313 +        vm_exit();
1314          return 0;
1315   }
1316   #endif
1317 +
1318 +
1319 +
1320 +
1321 +
1322 +
1323 +
1324 +
1325 +
1326 +
1327 +
1328 +
1329 +
1330 +
1331 +

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines