feec96271367ad03e4e0b0a8ff2c5ae0b78068ba
[sbcl.git] / src / runtime / x86-darwin-os.c
1
2
3 #ifdef LISP_FEATURE_SB_THREAD
4 #include <architecture/i386/table.h>
5 #include <i386/user_ldt.h>
6 #include <mach/mach_init.h>
7 #endif
8
9 #include "thread.h"
10 #include "validate.h"
11 #include "runtime.h"
12 #include "interrupt.h"
13 #include "x86-darwin-os.h"
14 #include "genesis/fdefn.h"
15
16 #include <mach/mach.h>
17 #include <mach/mach_error.h>
18 #include <mach/mach_types.h>
19 #include <mach/sync_policy.h>
20 #include <mach/machine/thread_state.h>
21 #include <mach/machine/thread_status.h>
22 #include <sys/_types.h>
23 #include <sys/ucontext.h>
24 #include <pthread.h>
25 #include <assert.h>
26 #include <stdlib.h>
27
28 #ifdef LISP_FEATURE_SB_THREAD
29
30 pthread_mutex_t modify_ldt_lock = PTHREAD_MUTEX_INITIALIZER;
31
32 void set_data_desc_size(data_desc_t* desc, unsigned long size)
33 {
34     desc->limit00 = (size - 1) & 0xffff;
35     desc->limit16 = ((size - 1) >> 16) &0xf;
36 }
37
38 void set_data_desc_addr(data_desc_t* desc, void* addr)
39 {
40     desc->base00 = (unsigned int)addr & 0xffff;
41     desc->base16 = ((unsigned int)addr & 0xff0000) >> 16;
42     desc->base24 = ((unsigned int)addr & 0xff000000) >> 24;
43 }
44
45 #endif
46
47 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
48 kern_return_t mach_thread_init(mach_port_t thread_exception_port);
49 #endif
50
51 int arch_os_thread_init(struct thread *thread) {
52 #ifdef LISP_FEATURE_SB_THREAD
53     int n;
54     sel_t sel;
55
56     data_desc_t ldt_entry = { 0, 0, 0, DESC_DATA_WRITE,
57                               3, 1, 0, DESC_DATA_32B, DESC_GRAN_BYTE, 0 };
58
59     set_data_desc_addr(&ldt_entry, thread);
60     set_data_desc_size(&ldt_entry, dynamic_values_bytes);
61
62     thread_mutex_lock(&modify_ldt_lock);
63     n = i386_set_ldt(LDT_AUTO_ALLOC, (union ldt_entry*) &ldt_entry, 1);
64
65     if (n < 0) {
66         perror("i386_set_ldt");
67         lose("unexpected i386_set_ldt(..) failure\n");
68     }
69     thread_mutex_unlock(&modify_ldt_lock);
70
71     FSHOW_SIGNAL((stderr, "/ TLS: Allocated LDT %x\n", n));
72     sel.index = n;
73     sel.rpl = USER_PRIV;
74     sel.ti = SEL_LDT;
75
76     __asm__ __volatile__ ("mov %0, %%fs" : : "r"(sel));
77
78     thread->tls_cookie=n;
79     pthread_setspecific(specials,thread);
80 #endif
81 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
82     mach_thread_init(THREAD_STRUCT_TO_EXCEPTION_PORT(thread));
83 #endif
84
85 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
86     stack_t sigstack;
87
88     /* Signal handlers are run on the control stack, so if it is exhausted
89      * we had better use an alternate stack for whatever signal tells us
90      * we've exhausted it */
91     sigstack.ss_sp=((void *) thread)+dynamic_values_bytes;
92     sigstack.ss_flags=0;
93     sigstack.ss_size = 32*SIGSTKSZ;
94     sigaltstack(&sigstack,0);
95 #endif
96     return 1;                  /* success */
97 }
98
99 int arch_os_thread_cleanup(struct thread *thread) {
100 #if defined(LISP_FEATURE_SB_THREAD)
101     int n = thread->tls_cookie;
102
103     /* Set the %%fs register back to 0 and free the the ldt
104      * by setting it to NULL.
105      */
106     FSHOW_SIGNAL((stderr, "/ TLS: Freeing LDT %x\n", n));
107
108     __asm__ __volatile__ ("mov %0, %%fs" : : "r"(0));
109     thread_mutex_lock(&modify_ldt_lock);
110     i386_set_ldt(n, NULL, 1);
111     thread_mutex_unlock(&modify_ldt_lock);
112 #endif
113     return 1;                  /* success */
114 }
115
116 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
117
118 void sigill_handler(int signal, siginfo_t *siginfo, void *void_context);
119 void sigtrap_handler(int signal, siginfo_t *siginfo, void *void_context);
120 void memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context);
121
122 /* exc_server handles mach exception messages from the kernel and
123  * calls catch exception raise. We use the system-provided
124  * mach_msg_server, which, I assume, calls exc_server in a loop.
125  *
126  */
127 extern boolean_t exc_server();
128
129 /* This executes in the faulting thread as part of the signal
130  * emulation.  It is passed a context with the uc_mcontext field
131  * pointing to a valid block of memory. */
132 void build_fake_signal_context(struct ucontext *context,
133                                x86_thread_state32_t *thread_state,
134                                x86_float_state32_t *float_state) {
135     pthread_sigmask(0, NULL, &context->uc_sigmask);
136     context->uc_mcontext->ss = *thread_state;
137     context->uc_mcontext->fs = *float_state;
138 }
139
140 /* This executes in the faulting thread as part of the signal
141  * emulation.  It is effectively the inverse operation from above. */
142 void update_thread_state_from_context(x86_thread_state32_t *thread_state,
143                                       x86_float_state32_t *float_state,
144                                       struct ucontext *context) {
145     *thread_state = context->uc_mcontext->ss;
146     *float_state = context->uc_mcontext->fs;
147     pthread_sigmask(SIG_SETMASK, &context->uc_sigmask, NULL);
148 }
149
150 /* Modify a context to push new data on its stack. */
151 void push_context(u32 data, x86_thread_state32_t *context)
152 {
153     u32 *stack_pointer;
154
155     stack_pointer = (u32*) context->esp;
156     *(--stack_pointer) = data;
157     context->esp = (unsigned int) stack_pointer;
158 }
159
160 void align_context_stack(x86_thread_state32_t *context)
161 {
162     /* 16byte align the stack (provided that the stack is, as it
163      * should be, 4byte aligned. */
164     while (context->esp & 15) push_context(0, context);
165 }
166
167 /* Stack allocation starts with a context that has a mod-4 ESP value
168  * and needs to leave a context with a mod-16 ESP that will restore
169  * the old ESP value and other register state when activated.  The
170  * first part of this is the recovery trampoline, which loads ESP from
171  * EBP, pops EBP, and returns. */
172 asm("_stack_allocation_recover: movl %ebp, %esp; popl %ebp; ret;");
173
174 void open_stack_allocation(x86_thread_state32_t *context)
175 {
176     void stack_allocation_recover(void);
177
178     push_context(context->eip, context);
179     push_context(context->ebp, context);
180     context->ebp = context->esp;
181     context->eip = (unsigned int) stack_allocation_recover;
182
183     align_context_stack(context);
184 }
185
186 /* Stack allocation of data starts with a context with a mod-16 ESP
187  * value and reserves some space on it by manipulating the ESP
188  * register. */
189 void *stack_allocate(x86_thread_state32_t *context, size_t size)
190 {
191     /* round up size to 16byte multiple */
192     size = (size + 15) & -16;
193
194     context->esp = ((u32)context->esp) - size;
195
196     return (void *)context->esp;
197 }
198
199 /* Arranging to invoke a C function is tricky, as we have to assume
200  * cdecl calling conventions (caller removes args) and x86/darwin
201  * alignment requirements.  The simplest way to arrange this,
202  * actually, is to open a new stack allocation.
203  * WARNING!!! THIS DOES NOT PRESERVE REGISTERS! */
204 void call_c_function_in_context(x86_thread_state32_t *context,
205                                 void *function,
206                                 int nargs,
207                                 ...)
208 {
209     va_list ap;
210     int i;
211     u32 *stack_pointer;
212
213     /* Set up to restore stack on exit. */
214     open_stack_allocation(context);
215
216     /* Have to keep stack 16byte aligned on x86/darwin. */
217     for (i = (3 & -nargs); i; i--) {
218         push_context(0, context);
219     }
220
221     context->esp = ((u32)context->esp) - nargs * 4;
222     stack_pointer = (u32 *)context->esp;
223
224     va_start(ap, nargs);
225     for (i = 0; i < nargs; i++) {
226         //push_context(va_arg(ap, u32), context);
227         stack_pointer[i] = va_arg(ap, u32);
228     }
229     va_end(ap);
230
231     push_context(context->eip, context);
232     context->eip = (unsigned int) function;
233 }
234
235 void signal_emulation_wrapper(x86_thread_state32_t *thread_state,
236                               x86_float_state32_t *float_state,
237                               int signal,
238                               siginfo_t *siginfo,
239                               void (*handler)(int, siginfo_t *, void *))
240 {
241
242     /* CLH: FIXME **NOTE: HACK ALERT!** Ideally, we would allocate
243      * context and regs on the stack as local variables, but this
244      * causes problems for the lisp debugger. When it walks the stack
245      * for a back trace, it sees the 1) address of the local variable
246      * on the stack and thinks that is a frame pointer to a lisp
247      * frame, and, 2) the address of the sap that we alloc'ed in
248      * dynamic space and thinks that is a return address, so it,
249      * heuristicly (and wrongly), chooses that this should be
250      * interpreted as a lisp frame instead of as a C frame.
251      * We can work around this in this case by os_validating the
252      * context (and regs just for symmetry).
253      */
254
255     struct ucontext *context;
256     struct mcontext *regs;
257     sigset_t sigmask;
258
259     context = (struct ucontext*) os_validate(0, sizeof(struct ucontext));
260     regs = (struct mcontext*) os_validate(0, sizeof(struct mcontext));
261     context->uc_mcontext = regs;
262
263     /* when BSD signals are fired, they mask they signals in sa_mask
264        which always seem to be the blockable_sigset, for us, so we
265        need to:
266        1) save the current sigmask
267        2) block blockable signals
268        3) call the signal handler
269        4) restore the sigmask */
270
271     pthread_sigmask(0, NULL, &sigmask);
272     block_blockable_signals();
273
274     build_fake_signal_context(context, thread_state, float_state);
275
276     handler(signal, siginfo, context);
277
278     update_thread_state_from_context(thread_state, float_state, context);
279
280     pthread_sigmask(SIG_SETMASK, &sigmask, NULL);
281
282     os_invalidate((os_vm_address_t)context, sizeof(struct ucontext));
283     os_invalidate((os_vm_address_t)regs, sizeof(struct mcontext));
284
285     /* Trap to restore the signal context. */
286     asm volatile ("movl %0, %%eax; .long 0xffff0b0f": : "r" (thread_state));
287 }
288
289 #if defined DUMP_CONTEXT
290 void dump_context(x86_thread_state32_t *context)
291 {
292     int i;
293     u32 *stack_pointer;
294
295     printf("eax: %08lx  ecx: %08lx  edx: %08lx  ebx: %08lx\n",
296            context->eax, context->ecx, context->edx, context->ebx);
297     printf("esp: %08lx  ebp: %08lx  esi: %08lx  edi: %08lx\n",
298            context->esp, context->ebp, context->esi, context->edi);
299     printf("eip: %08lx  eflags: %08lx\n",
300            context->eip, context->eflags);
301     printf("cs: %04hx  ds: %04hx  es: %04hx  "
302            "ss: %04hx  fs: %04hx  gs: %04hx\n",
303            context->cs, context->ds, context->es,
304            context->ss, context->fs, context->gs);
305
306     stack_pointer = (u32 *)context->esp;
307     for (i = 0; i < 48; i+=4) {
308         printf("%08x:  %08x %08x %08x %08x\n",
309                context->esp + (i * 4),
310                stack_pointer[i],
311                stack_pointer[i+1],
312                stack_pointer[i+2],
313                stack_pointer[i+3]);
314     }
315 }
316 #endif
317
318 void
319 control_stack_exhausted_handler(int signal, siginfo_t *siginfo, void *void_context) {
320     os_context_t *context = arch_os_get_context(&void_context);
321
322     arrange_return_to_lisp_function
323         (context, SymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
324 }
325
326 void
327 undefined_alien_handler(int signal, siginfo_t *siginfo, void *void_context) {
328     os_context_t *context = arch_os_get_context(&void_context);
329
330     arrange_return_to_lisp_function
331         (context, SymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
332 }
333
334 kern_return_t
335 catch_exception_raise(mach_port_t exception_port,
336                      mach_port_t thread,
337                      mach_port_t task,
338                      exception_type_t exception,
339                      exception_data_t code_vector,
340                      mach_msg_type_number_t code_count)
341 {
342     kern_return_t ret;
343     int signal;
344     siginfo_t* siginfo;
345
346     x86_thread_state32_t thread_state;
347     mach_msg_type_number_t thread_state_count = x86_THREAD_STATE32_COUNT;
348
349     x86_float_state32_t float_state;
350     mach_msg_type_number_t float_state_count = x86_FLOAT_STATE32_COUNT;
351
352     x86_exception_state32_t exception_state;
353     mach_msg_type_number_t exception_state_count = x86_EXCEPTION_STATE32_COUNT;
354
355     x86_thread_state32_t backup_thread_state;
356     x86_thread_state32_t *target_thread_state;
357     x86_float_state32_t *target_float_state;
358
359     os_vm_address_t addr;
360
361     struct thread *th = (struct thread*) exception_port;
362
363     FSHOW((stderr,"/entering catch_exception_raise with exception: %d\n", exception));
364
365     switch (exception) {
366
367     case EXC_BAD_ACCESS:
368         signal = SIGBUS;
369         ret = thread_get_state(thread,
370                                x86_THREAD_STATE32,
371                                (thread_state_t)&thread_state,
372                                &thread_state_count);
373         ret = thread_get_state(thread,
374                                x86_FLOAT_STATE32,
375                                (thread_state_t)&float_state,
376                                &float_state_count);
377         ret = thread_get_state(thread,
378                                x86_EXCEPTION_STATE32,
379                                (thread_state_t)&exception_state,
380                                &exception_state_count);
381         addr = (void*)exception_state.faultvaddr;
382
383
384         /* note the os_context hackery here.  When the signal handler returns,
385          * it won't go back to what it was doing ... */
386         if(addr >= CONTROL_STACK_GUARD_PAGE(th) &&
387            addr < CONTROL_STACK_GUARD_PAGE(th) + os_vm_page_size) {
388             /* We hit the end of the control stack: disable guard page
389              * protection so the error handler has some headroom, protect the
390              * previous page so that we can catch returns from the guard page
391              * and restore it. */
392             protect_control_stack_guard_page_thread(0, th);
393             protect_control_stack_return_guard_page_thread(1, th);
394
395             backup_thread_state = thread_state;
396             open_stack_allocation(&thread_state);
397
398             /* Save thread state */
399             target_thread_state =
400                 stack_allocate(&thread_state, sizeof(*target_thread_state));
401             (*target_thread_state) = backup_thread_state;
402
403             /* Save float state */
404             target_float_state =
405                 stack_allocate(&thread_state, sizeof(*target_float_state));
406             (*target_float_state) = float_state;
407
408             /* Set up siginfo */
409             siginfo = stack_allocate(&thread_state, sizeof(*siginfo));
410             /* what do we need to put in our fake siginfo?  It looks like
411              * the x86 code only uses si_signo and si_adrr. */
412             siginfo->si_signo = signal;
413             siginfo->si_addr = (void*)exception_state.faultvaddr;
414
415             call_c_function_in_context(&thread_state,
416                                        signal_emulation_wrapper,
417                                        5,
418                                        target_thread_state,
419                                        target_float_state,
420                                        signal,
421                                        siginfo,
422                                        control_stack_exhausted_handler);
423         }
424         else if(addr >= CONTROL_STACK_RETURN_GUARD_PAGE(th) &&
425                 addr < CONTROL_STACK_RETURN_GUARD_PAGE(th) + os_vm_page_size) {
426             /* We're returning from the guard page: reprotect it, and
427              * unprotect this one. This works even if we somehow missed
428              * the return-guard-page, and hit it on our way to new
429              * exhaustion instead. */
430             protect_control_stack_guard_page_thread(1, th);
431             protect_control_stack_return_guard_page_thread(0, th);
432
433         }
434         else if (addr >= undefined_alien_address &&
435                  addr < undefined_alien_address + os_vm_page_size) {
436             backup_thread_state = thread_state;
437             open_stack_allocation(&thread_state);
438
439             /* Save thread state */
440             target_thread_state =
441                 stack_allocate(&thread_state, sizeof(*target_thread_state));
442             (*target_thread_state) = backup_thread_state;
443
444             target_float_state =
445                 stack_allocate(&thread_state, sizeof(*target_float_state));
446             (*target_float_state) = float_state;
447
448             /* Set up siginfo */
449             siginfo = stack_allocate(&thread_state, sizeof(*siginfo));
450             /* what do we need to put in our fake siginfo?  It looks like
451              * the x86 code only uses si_signo and si_adrr. */
452             siginfo->si_signo = signal;
453             siginfo->si_addr = (void*)exception_state.faultvaddr;
454
455             call_c_function_in_context(&thread_state,
456                                        signal_emulation_wrapper,
457                                        5,
458                                        target_thread_state,
459                                        target_float_state,
460                                        signal,
461                                        siginfo,
462                                        undefined_alien_handler);
463         } else {
464
465             backup_thread_state = thread_state;
466             open_stack_allocation(&thread_state);
467
468             /* Save thread state */
469             target_thread_state =
470                 stack_allocate(&thread_state, sizeof(*target_thread_state));
471             (*target_thread_state) = backup_thread_state;
472
473             target_float_state =
474                 stack_allocate(&thread_state, sizeof(*target_float_state));
475             (*target_float_state) = float_state;
476
477             /* Set up siginfo */
478             siginfo = stack_allocate(&thread_state, sizeof(*siginfo));
479             /* what do we need to put in our fake siginfo?  It looks like
480              * the x86 code only uses si_signo and si_adrr. */
481             siginfo->si_signo = signal;
482             siginfo->si_addr = (void*)exception_state.faultvaddr;
483
484             call_c_function_in_context(&thread_state,
485                                        signal_emulation_wrapper,
486                                        5,
487                                        target_thread_state,
488                                        target_float_state,
489                                        signal,
490                                        siginfo,
491                                        memory_fault_handler);
492         }
493         ret = thread_set_state(thread,
494                                x86_THREAD_STATE32,
495                                (thread_state_t)&thread_state,
496                                thread_state_count);
497
498         ret = thread_set_state(thread,
499                                x86_FLOAT_STATE32,
500                                (thread_state_t)&float_state,
501                                float_state_count);
502         return KERN_SUCCESS;
503
504     case EXC_BAD_INSTRUCTION:
505
506         ret = thread_get_state(thread,
507                                x86_THREAD_STATE32,
508                                (thread_state_t)&thread_state,
509                                &thread_state_count);
510         ret = thread_get_state(thread,
511                                x86_FLOAT_STATE32,
512                                (thread_state_t)&float_state,
513                                &float_state_count);
514         ret = thread_get_state(thread,
515                                x86_EXCEPTION_STATE32,
516                                (thread_state_t)&exception_state,
517                                &exception_state_count);
518         if (0xffff0b0f == *((u32 *)thread_state.eip)) {
519             /* fake sigreturn. */
520
521             /* When we get here, thread_state.eax is a pointer to a
522              * thread_state to restore. */
523             /* thread_state = *((thread_state_t *)thread_state.eax); */
524
525             ret = thread_set_state(thread,
526                                    x86_THREAD_STATE32,
527                                    (thread_state_t) thread_state.eax,
528                                    /* &thread_state, */
529                                    thread_state_count);
530         } else {
531
532             backup_thread_state = thread_state;
533             open_stack_allocation(&thread_state);
534
535             /* Save thread state */
536             target_thread_state =
537                 stack_allocate(&thread_state, sizeof(*target_thread_state));
538             (*target_thread_state) = backup_thread_state;
539
540             target_float_state =
541                 stack_allocate(&thread_state, sizeof(*target_float_state));
542             (*target_float_state) = float_state;
543
544             /* Set up siginfo */
545             siginfo = stack_allocate(&thread_state, sizeof(*siginfo));
546             /* what do we need to put in our fake siginfo?  It looks like
547              * the x86 code only uses si_signo and si_adrr. */
548             if (*((unsigned short *)target_thread_state->eip) == 0x0b0f) {
549                 signal = SIGTRAP;
550                 siginfo->si_signo = signal;
551                 siginfo->si_addr = (void*)exception_state.faultvaddr;
552                 target_thread_state->eip += 2;
553                 call_c_function_in_context(&thread_state,
554                                            signal_emulation_wrapper,
555                                            5,
556                                            target_thread_state,
557                                            target_float_state,
558                                            signal,
559                                            siginfo,
560                                            sigtrap_handler);
561             } else {
562                 signal = SIGILL;
563                 siginfo->si_signo = signal;
564                 siginfo->si_addr = (void*)exception_state.faultvaddr;
565
566                 call_c_function_in_context(&thread_state,
567                                            signal_emulation_wrapper,
568                                            5,
569                                            target_thread_state,
570                                            target_float_state,
571                                            signal,
572                                            siginfo,
573                                            sigill_handler);
574             }
575             ret = thread_set_state(thread,
576                                    x86_THREAD_STATE32,
577                                    (thread_state_t)&thread_state,
578                                    thread_state_count);
579             ret = thread_set_state(thread,
580                                    x86_FLOAT_STATE32,
581                                    (thread_state_t)&float_state,
582                                    float_state_count);
583         }
584         return KERN_SUCCESS;
585
586     default:
587         return KERN_INVALID_RIGHT;
588     }
589 }
590
591 void *
592 mach_exception_handler(void *port)
593 {
594   mach_msg_server(exc_server, 2048, (mach_port_t) port, 0);
595   /* mach_msg_server should never return, but it should dispatch mach
596    * exceptions to our catch_exception_raise function
597    */
598   abort();
599 }
600
601 #endif
602
603 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
604
605 /* Sets up the thread that will listen for mach exceptions. note that
606    the exception handlers will be run on this thread. This is
607    different from the BSD-style signal handling situation in which the
608    signal handlers run in the relevant thread directly. */
609
610 mach_port_t mach_exception_handler_port_set = MACH_PORT_NULL;
611
612 pthread_t
613 setup_mach_exception_handling_thread()
614 {
615     kern_return_t ret;
616     pthread_t mach_exception_handling_thread = NULL;
617     pthread_attr_t attr;
618
619     /* allocate a mach_port for this process */
620     ret = mach_port_allocate(mach_task_self(),
621                              MACH_PORT_RIGHT_PORT_SET,
622                              &mach_exception_handler_port_set);
623
624     /* create the thread that will receive the mach exceptions */
625
626     FSHOW((stderr, "Creating mach_exception_handler thread!\n"));
627
628     pthread_attr_init(&attr);
629     pthread_create(&mach_exception_handling_thread,
630                    &attr,
631                    mach_exception_handler,
632                    (void*) mach_exception_handler_port_set);
633     pthread_attr_destroy(&attr);
634
635     return mach_exception_handling_thread;
636 }
637
638 /* tell the kernel that we want EXC_BAD_ACCESS exceptions sent to the
639    exception port (which is being listened to do by the mach
640    exception handling thread). */
641 kern_return_t
642 mach_thread_init(mach_port_t thread_exception_port)
643 {
644     kern_return_t ret;
645     /* allocate a named port for the thread */
646
647     FSHOW((stderr, "Allocating mach port %x\n", thread_exception_port));
648
649     ret = mach_port_allocate_name(mach_task_self(),
650                                   MACH_PORT_RIGHT_RECEIVE,
651                                   thread_exception_port);
652     if (ret) {
653         lose("mach_port_allocate_name failed with return_code %d\n", ret);
654     }
655
656     /* establish the right for the thread_exception_port to send messages */
657     ret = mach_port_insert_right(mach_task_self(),
658                                  thread_exception_port,
659                                  thread_exception_port,
660                                  MACH_MSG_TYPE_MAKE_SEND);
661     if (ret) {
662         lose("mach_port_insert_right failed with return_code %d\n", ret);
663     }
664
665     ret = thread_set_exception_ports(mach_thread_self(),
666                                      EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION,
667                                      thread_exception_port,
668                                      EXCEPTION_DEFAULT,
669                                      THREAD_STATE_NONE);
670     if (ret) {
671         lose("thread_set_exception_port failed with return_code %d\n", ret);
672     }
673
674     ret = mach_port_move_member(mach_task_self(),
675                                 thread_exception_port,
676                                 mach_exception_handler_port_set);
677     if (ret) {
678         lose("mach_port_ failed with return_code %d\n", ret);
679     }
680
681     return ret;
682 }
683
684 void
685 setup_mach_exceptions() {
686     setup_mach_exception_handling_thread();
687     mach_thread_init(THREAD_STRUCT_TO_EXCEPTION_PORT(all_threads));
688 }
689
690 pid_t
691 mach_fork() {
692     pid_t pid = fork();
693     if (pid == 0) {
694         setup_mach_exceptions();
695         return pid;
696     } else {
697         return pid;
698     }
699 }
700
701 #endif