ViewVC Help
View File | Revision Log | Show Annotations | Revision Graph | Root Listing
root/cebix/BasiliskII/src/Unix/sigsegv.cpp
Revision: 1.34
Committed: 2003-11-10T23:47:39Z (21 years ago) by gbeauche
Branch: MAIN
Changes since 1.33: +197 -36 lines
Log Message:
Extend x86 instruction skipper to AMD64. Add plenty of arch dependent
opcodes to test it. Also fix DEBUG output & writes (zero'ing) to %xH regs

File Contents

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