3 #ifdef LISP_FEATURE_SB_THREAD
4 #include <architecture/i386/table.h>
5 #include <i386/user_ldt.h>
6 #include <mach/mach_init.h>
12 #include "interrupt.h"
13 #include "x86-darwin-os.h"
14 #include "genesis/fdefn.h"
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>
28 #ifdef LISP_FEATURE_SB_THREAD
30 pthread_mutex_t modify_ldt_lock = PTHREAD_MUTEX_INITIALIZER;
31 pthread_mutex_t mach_exception_lock = PTHREAD_MUTEX_INITIALIZER;
33 void set_data_desc_size(data_desc_t* desc, unsigned long size)
35 desc->limit00 = (size - 1) & 0xffff;
36 desc->limit16 = ((size - 1) >> 16) &0xf;
39 void set_data_desc_addr(data_desc_t* desc, void* addr)
41 desc->base00 = (unsigned int)addr & 0xffff;
42 desc->base16 = ((unsigned int)addr & 0xff0000) >> 16;
43 desc->base24 = ((unsigned int)addr & 0xff000000) >> 24;
48 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
49 kern_return_t mach_thread_init(mach_port_t thread_exception_port);
52 int arch_os_thread_init(struct thread *thread) {
53 #ifdef LISP_FEATURE_SB_THREAD
57 data_desc_t ldt_entry = { 0, 0, 0, DESC_DATA_WRITE,
58 3, 1, 0, DESC_DATA_32B, DESC_GRAN_BYTE, 0 };
60 set_data_desc_addr(&ldt_entry, thread);
61 set_data_desc_size(&ldt_entry, dynamic_values_bytes);
63 thread_mutex_lock(&modify_ldt_lock);
64 n = i386_set_ldt(LDT_AUTO_ALLOC, (union ldt_entry*) &ldt_entry, 1);
67 perror("i386_set_ldt");
68 lose("unexpected i386_set_ldt(..) failure\n");
70 thread_mutex_unlock(&modify_ldt_lock);
72 FSHOW_SIGNAL((stderr, "/ TLS: Allocated LDT %x\n", n));
77 __asm__ __volatile__ ("mov %0, %%fs" : : "r"(sel));
80 pthread_setspecific(specials,thread);
82 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
83 mach_thread_init(THREAD_STRUCT_TO_EXCEPTION_PORT(thread));
86 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
89 /* Signal handlers are run on the control stack, so if it is exhausted
90 * we had better use an alternate stack for whatever signal tells us
91 * we've exhausted it */
92 sigstack.ss_sp=((void *) thread)+dynamic_values_bytes;
94 sigstack.ss_size = 32*SIGSTKSZ;
95 sigaltstack(&sigstack,0);
97 return 1; /* success */
100 int arch_os_thread_cleanup(struct thread *thread) {
101 #if defined(LISP_FEATURE_SB_THREAD)
102 int n = thread->tls_cookie;
104 /* Set the %%fs register back to 0 and free the the ldt
105 * by setting it to NULL.
107 FSHOW_SIGNAL((stderr, "/ TLS: Freeing LDT %x\n", n));
109 __asm__ __volatile__ ("mov %0, %%fs" : : "r"(0));
110 thread_mutex_lock(&modify_ldt_lock);
111 i386_set_ldt(n, NULL, 1);
112 thread_mutex_unlock(&modify_ldt_lock);
114 return 1; /* success */
117 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
119 void sigill_handler(int signal, siginfo_t *siginfo, void *void_context);
120 void sigtrap_handler(int signal, siginfo_t *siginfo, void *void_context);
121 void memory_fault_handler(int signal, siginfo_t *siginfo, void *void_context);
123 /* exc_server handles mach exception messages from the kernel and
124 * calls catch exception raise. We use the system-provided
125 * mach_msg_server, which, I assume, calls exc_server in a loop.
128 extern boolean_t exc_server();
130 /* This executes in the faulting thread as part of the signal
131 * emulation. It is passed a context with the uc_mcontext field
132 * pointing to a valid block of memory. */
133 void build_fake_signal_context(struct ucontext *context,
134 x86_thread_state32_t *thread_state,
135 x86_float_state32_t *float_state) {
136 pthread_sigmask(0, NULL, &context->uc_sigmask);
137 context->uc_mcontext->ss = *thread_state;
138 context->uc_mcontext->fs = *float_state;
141 /* This executes in the faulting thread as part of the signal
142 * emulation. It is effectively the inverse operation from above. */
143 void update_thread_state_from_context(x86_thread_state32_t *thread_state,
144 x86_float_state32_t *float_state,
145 struct ucontext *context) {
146 *thread_state = context->uc_mcontext->ss;
147 *float_state = context->uc_mcontext->fs;
148 pthread_sigmask(SIG_SETMASK, &context->uc_sigmask, NULL);
151 /* Modify a context to push new data on its stack. */
152 void push_context(u32 data, x86_thread_state32_t *context)
156 stack_pointer = (u32*) context->esp;
157 *(--stack_pointer) = data;
158 context->esp = (unsigned int) stack_pointer;
161 void align_context_stack(x86_thread_state32_t *context)
163 /* 16byte align the stack (provided that the stack is, as it
164 * should be, 4byte aligned. */
165 while (context->esp & 15) push_context(0, context);
168 /* Stack allocation starts with a context that has a mod-4 ESP value
169 * and needs to leave a context with a mod-16 ESP that will restore
170 * the old ESP value and other register state when activated. The
171 * first part of this is the recovery trampoline, which loads ESP from
172 * EBP, pops EBP, and returns. */
173 asm("_stack_allocation_recover: movl %ebp, %esp; popl %ebp; ret;");
175 void open_stack_allocation(x86_thread_state32_t *context)
177 void stack_allocation_recover(void);
179 push_context(context->eip, context);
180 push_context(context->ebp, context);
181 context->ebp = context->esp;
182 context->eip = (unsigned int) stack_allocation_recover;
184 align_context_stack(context);
187 /* Stack allocation of data starts with a context with a mod-16 ESP
188 * value and reserves some space on it by manipulating the ESP
190 void *stack_allocate(x86_thread_state32_t *context, size_t size)
192 /* round up size to 16byte multiple */
193 size = (size + 15) & -16;
195 context->esp = ((u32)context->esp) - size;
197 return (void *)context->esp;
200 /* Arranging to invoke a C function is tricky, as we have to assume
201 * cdecl calling conventions (caller removes args) and x86/darwin
202 * alignment requirements. The simplest way to arrange this,
203 * actually, is to open a new stack allocation.
204 * WARNING!!! THIS DOES NOT PRESERVE REGISTERS! */
205 void call_c_function_in_context(x86_thread_state32_t *context,
214 /* Set up to restore stack on exit. */
215 open_stack_allocation(context);
217 /* Have to keep stack 16byte aligned on x86/darwin. */
218 for (i = (3 & -nargs); i; i--) {
219 push_context(0, context);
222 context->esp = ((u32)context->esp) - nargs * 4;
223 stack_pointer = (u32 *)context->esp;
226 for (i = 0; i < nargs; i++) {
227 //push_context(va_arg(ap, u32), context);
228 stack_pointer[i] = va_arg(ap, u32);
232 push_context(context->eip, context);
233 context->eip = (unsigned int) function;
236 void signal_emulation_wrapper(x86_thread_state32_t *thread_state,
237 x86_float_state32_t *float_state,
240 void (*handler)(int, siginfo_t *, void *))
243 /* CLH: FIXME **NOTE: HACK ALERT!** Ideally, we would allocate
244 * context and regs on the stack as local variables, but this
245 * causes problems for the lisp debugger. When it walks the stack
246 * for a back trace, it sees the 1) address of the local variable
247 * on the stack and thinks that is a frame pointer to a lisp
248 * frame, and, 2) the address of the sap that we alloc'ed in
249 * dynamic space and thinks that is a return address, so it,
250 * heuristicly (and wrongly), chooses that this should be
251 * interpreted as a lisp frame instead of as a C frame.
252 * We can work around this in this case by os_validating the
253 * context (and regs just for symmetry).
256 struct ucontext *context;
257 struct mcontext *regs;
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;
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
266 1) save the current sigmask
267 2) block blockable signals
268 3) call the signal handler
269 4) restore the sigmask */
271 build_fake_signal_context(context, thread_state, float_state);
273 block_blockable_signals();
275 handler(signal, siginfo, context);
277 update_thread_state_from_context(thread_state, float_state, context);
279 os_invalidate((os_vm_address_t)context, sizeof(struct ucontext));
280 os_invalidate((os_vm_address_t)regs, sizeof(struct mcontext));
282 /* Trap to restore the signal context. */
283 asm volatile ("movl %0, %%eax; movl %1, %%ebx; .long 0xffff0b0f"
284 : : "r" (thread_state), "r" (float_state));
287 #if defined DUMP_CONTEXT
288 void dump_context(x86_thread_state32_t *context)
293 printf("eax: %08lx ecx: %08lx edx: %08lx ebx: %08lx\n",
294 context->eax, context->ecx, context->edx, context->ebx);
295 printf("esp: %08lx ebp: %08lx esi: %08lx edi: %08lx\n",
296 context->esp, context->ebp, context->esi, context->edi);
297 printf("eip: %08lx eflags: %08lx\n",
298 context->eip, context->eflags);
299 printf("cs: %04hx ds: %04hx es: %04hx "
300 "ss: %04hx fs: %04hx gs: %04hx\n",
301 context->cs, context->ds, context->es,
302 context->ss, context->fs, context->gs);
304 stack_pointer = (u32 *)context->esp;
305 for (i = 0; i < 48; i+=4) {
306 printf("%08x: %08x %08x %08x %08x\n",
307 context->esp + (i * 4),
317 control_stack_exhausted_handler(int signal, siginfo_t *siginfo, void *void_context) {
318 os_context_t *context = arch_os_get_context(&void_context);
320 arrange_return_to_lisp_function
321 (context, SymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
325 undefined_alien_handler(int signal, siginfo_t *siginfo, void *void_context) {
326 os_context_t *context = arch_os_get_context(&void_context);
328 arrange_return_to_lisp_function
329 (context, SymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
333 catch_exception_raise(mach_port_t exception_port,
336 exception_type_t exception,
337 exception_data_t code_vector,
338 mach_msg_type_number_t code_count)
344 thread_mutex_lock(&mach_exception_lock);
346 x86_thread_state32_t thread_state;
347 mach_msg_type_number_t thread_state_count = x86_THREAD_STATE32_COUNT;
349 x86_float_state32_t float_state;
350 mach_msg_type_number_t float_state_count = x86_FLOAT_STATE32_COUNT;
352 x86_exception_state32_t exception_state;
353 mach_msg_type_number_t exception_state_count = x86_EXCEPTION_STATE32_COUNT;
355 x86_thread_state32_t backup_thread_state;
356 x86_thread_state32_t *target_thread_state;
357 x86_float_state32_t *target_float_state;
359 os_vm_address_t addr;
361 struct thread *th = (struct thread*) exception_port;
363 FSHOW((stderr,"/entering catch_exception_raise with exception: %d\n", exception));
369 ret = thread_get_state(thread,
371 (thread_state_t)&thread_state,
372 &thread_state_count);
373 ret = thread_get_state(thread,
375 (thread_state_t)&float_state,
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;
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
392 protect_control_stack_guard_page_thread(0, th);
393 protect_control_stack_return_guard_page_thread(1, th);
395 backup_thread_state = thread_state;
396 open_stack_allocation(&thread_state);
398 /* Save thread state */
399 target_thread_state =
400 stack_allocate(&thread_state, sizeof(*target_thread_state));
401 (*target_thread_state) = backup_thread_state;
403 /* Save float state */
405 stack_allocate(&thread_state, sizeof(*target_float_state));
406 (*target_float_state) = float_state;
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;
415 call_c_function_in_context(&thread_state,
416 signal_emulation_wrapper,
422 control_stack_exhausted_handler);
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);
433 else if (addr >= undefined_alien_address &&
434 addr < undefined_alien_address + os_vm_page_size) {
435 backup_thread_state = thread_state;
436 open_stack_allocation(&thread_state);
438 /* Save thread state */
439 target_thread_state =
440 stack_allocate(&thread_state, sizeof(*target_thread_state));
441 (*target_thread_state) = backup_thread_state;
444 stack_allocate(&thread_state, sizeof(*target_float_state));
445 (*target_float_state) = float_state;
448 siginfo = stack_allocate(&thread_state, sizeof(*siginfo));
449 /* what do we need to put in our fake siginfo? It looks like
450 * the x86 code only uses si_signo and si_adrr. */
451 siginfo->si_signo = signal;
452 siginfo->si_addr = (void*)exception_state.faultvaddr;
454 call_c_function_in_context(&thread_state,
455 signal_emulation_wrapper,
461 undefined_alien_handler);
464 backup_thread_state = thread_state;
465 open_stack_allocation(&thread_state);
467 /* Save thread state */
468 target_thread_state =
469 stack_allocate(&thread_state, sizeof(*target_thread_state));
470 (*target_thread_state) = backup_thread_state;
473 stack_allocate(&thread_state, sizeof(*target_float_state));
474 (*target_float_state) = float_state;
477 siginfo = stack_allocate(&thread_state, sizeof(*siginfo));
478 /* what do we need to put in our fake siginfo? It looks like
479 * the x86 code only uses si_signo and si_adrr. */
480 siginfo->si_signo = signal;
481 siginfo->si_addr = (void*)exception_state.faultvaddr;
483 call_c_function_in_context(&thread_state,
484 signal_emulation_wrapper,
490 memory_fault_handler);
492 ret = thread_set_state(thread,
494 (thread_state_t)&thread_state,
497 ret = thread_set_state(thread,
499 (thread_state_t)&float_state,
501 thread_mutex_unlock(&mach_exception_lock);
504 case EXC_BAD_INSTRUCTION:
506 ret = thread_get_state(thread,
508 (thread_state_t)&thread_state,
509 &thread_state_count);
510 ret = thread_get_state(thread,
512 (thread_state_t)&float_state,
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. */
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); */
525 ret = thread_set_state(thread,
527 (thread_state_t) thread_state.eax,
531 ret = thread_set_state(thread,
533 (thread_state_t) thread_state.ebx,
538 backup_thread_state = thread_state;
539 open_stack_allocation(&thread_state);
541 /* Save thread state */
542 target_thread_state =
543 stack_allocate(&thread_state, sizeof(*target_thread_state));
544 (*target_thread_state) = backup_thread_state;
547 stack_allocate(&thread_state, sizeof(*target_float_state));
548 (*target_float_state) = float_state;
551 siginfo = stack_allocate(&thread_state, sizeof(*siginfo));
552 /* what do we need to put in our fake siginfo? It looks like
553 * the x86 code only uses si_signo and si_adrr. */
554 if (*((unsigned short *)target_thread_state->eip) == 0x0b0f) {
556 siginfo->si_signo = signal;
557 siginfo->si_addr = (void*)exception_state.faultvaddr;
558 target_thread_state->eip += 2;
559 call_c_function_in_context(&thread_state,
560 signal_emulation_wrapper,
569 siginfo->si_signo = signal;
570 siginfo->si_addr = (void*)exception_state.faultvaddr;
572 call_c_function_in_context(&thread_state,
573 signal_emulation_wrapper,
581 ret = thread_set_state(thread,
583 (thread_state_t)&thread_state,
585 ret = thread_set_state(thread,
587 (thread_state_t)&float_state,
590 thread_mutex_unlock(&mach_exception_lock);
594 thread_mutex_unlock(&mach_exception_lock);
595 return KERN_INVALID_RIGHT;
600 mach_exception_handler(void *port)
602 mach_msg_server(exc_server, 2048, (mach_port_t) port, 0);
603 /* mach_msg_server should never return, but it should dispatch mach
604 * exceptions to our catch_exception_raise function
611 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
613 /* Sets up the thread that will listen for mach exceptions. note that
614 the exception handlers will be run on this thread. This is
615 different from the BSD-style signal handling situation in which the
616 signal handlers run in the relevant thread directly. */
618 mach_port_t mach_exception_handler_port_set = MACH_PORT_NULL;
621 setup_mach_exception_handling_thread()
624 pthread_t mach_exception_handling_thread = NULL;
627 /* allocate a mach_port for this process */
628 ret = mach_port_allocate(mach_task_self(),
629 MACH_PORT_RIGHT_PORT_SET,
630 &mach_exception_handler_port_set);
632 /* create the thread that will receive the mach exceptions */
634 FSHOW((stderr, "Creating mach_exception_handler thread!\n"));
636 pthread_attr_init(&attr);
637 pthread_create(&mach_exception_handling_thread,
639 mach_exception_handler,
640 (void*) mach_exception_handler_port_set);
641 pthread_attr_destroy(&attr);
643 return mach_exception_handling_thread;
646 /* tell the kernel that we want EXC_BAD_ACCESS exceptions sent to the
647 exception port (which is being listened to do by the mach
648 exception handling thread). */
650 mach_thread_init(mach_port_t thread_exception_port)
653 /* allocate a named port for the thread */
655 FSHOW((stderr, "Allocating mach port %x\n", thread_exception_port));
657 ret = mach_port_allocate_name(mach_task_self(),
658 MACH_PORT_RIGHT_RECEIVE,
659 thread_exception_port);
661 lose("mach_port_allocate_name failed with return_code %d\n", ret);
664 /* establish the right for the thread_exception_port to send messages */
665 ret = mach_port_insert_right(mach_task_self(),
666 thread_exception_port,
667 thread_exception_port,
668 MACH_MSG_TYPE_MAKE_SEND);
670 lose("mach_port_insert_right failed with return_code %d\n", ret);
673 ret = thread_set_exception_ports(mach_thread_self(),
674 EXC_MASK_BAD_ACCESS | EXC_MASK_BAD_INSTRUCTION,
675 thread_exception_port,
679 lose("thread_set_exception_port failed with return_code %d\n", ret);
682 ret = mach_port_move_member(mach_task_self(),
683 thread_exception_port,
684 mach_exception_handler_port_set);
686 lose("mach_port_ failed with return_code %d\n", ret);
693 setup_mach_exceptions() {
694 setup_mach_exception_handling_thread();
695 mach_thread_init(THREAD_STRUCT_TO_EXCEPTION_PORT(all_threads));
702 setup_mach_exceptions();