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.7 by cebix, 2002-01-15T14:58:37Z vs.
Revision 1.30 by gbeauche, 2003-10-13T19:56:17Z

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines