Fix building on older OSX.
[sbcl.git] / src / runtime / x86-darwin-os.c
blob19e5e376cc3959cd5cdd977a09948d51baeaebe1
1 #ifdef LISP_FEATURE_SB_THREAD
2 #include <architecture/i386/table.h>
3 #include <i386/user_ldt.h>
4 #include <mach/mach_init.h>
5 #endif
7 #include "thread.h"
8 #include "validate.h"
9 #include "runtime.h"
10 #include "interrupt.h"
11 #include "x86-darwin-os.h"
12 #include "genesis/fdefn.h"
14 #include <mach/mach.h>
15 #include <mach/mach_error.h>
16 #include <mach/mach_types.h>
17 #include <mach/sync_policy.h>
18 #include <mach/vm_region.h>
19 #include <mach/machine/thread_state.h>
20 #include <mach/machine/thread_status.h>
21 #include <sys/_types.h>
22 #include <sys/ucontext.h>
23 #include <pthread.h>
24 #include <assert.h>
25 #include <stdlib.h>
26 #include <stdio.h>
28 #ifdef LISP_FEATURE_SB_THREAD
30 pthread_mutex_t modify_ldt_lock = PTHREAD_MUTEX_INITIALIZER;
32 void set_data_desc_size(data_desc_t* desc, unsigned long size)
34 desc->limit00 = (size - 1) & 0xffff;
35 desc->limit16 = ((size - 1) >> 16) &0xf;
38 void set_data_desc_addr(data_desc_t* desc, void* addr)
40 desc->base00 = (unsigned int)addr & 0xffff;
41 desc->base16 = ((unsigned int)addr & 0xff0000) >> 16;
42 desc->base24 = ((unsigned int)addr & 0xff000000) >> 24;
45 #endif
47 #ifdef LISP_FEATURE_SB_THREAD
48 void
49 arch_os_load_ldt(struct thread *thread)
51 sel_t sel;
53 sel.index = thread->tls_cookie;
54 sel.rpl = USER_PRIV;
55 sel.ti = SEL_LDT;
57 __asm__ __volatile__ ("mov %0, %%fs" : : "r"(sel));
59 #endif
61 int arch_os_thread_init(struct thread *thread) {
62 #ifdef LISP_FEATURE_SB_THREAD
63 int n;
65 data_desc_t ldt_entry = { 0, 0, 0, DESC_DATA_WRITE,
66 3, 1, 0, DESC_DATA_32B, DESC_GRAN_BYTE, 0 };
68 set_data_desc_addr(&ldt_entry, thread);
69 set_data_desc_size(&ldt_entry, dynamic_values_bytes);
71 thread_mutex_lock(&modify_ldt_lock);
72 n = i386_set_ldt(LDT_AUTO_ALLOC, (union ldt_entry*) &ldt_entry, 1);
74 if (n < 0) {
75 perror("i386_set_ldt");
76 lose("unexpected i386_set_ldt(..) failure\n");
78 thread_mutex_unlock(&modify_ldt_lock);
80 FSHOW_SIGNAL((stderr, "/ TLS: Allocated LDT %x\n", n));
81 thread->tls_cookie=n;
82 arch_os_load_ldt(thread);
84 pthread_setspecific(specials,thread);
85 #endif
86 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
87 mach_lisp_thread_init(thread);
88 #endif
90 #ifdef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
91 stack_t sigstack;
93 /* Signal handlers are run on the control stack, so if it is exhausted
94 * we had better use an alternate stack for whatever signal tells us
95 * we've exhausted it */
96 sigstack.ss_sp=((void *) thread)+dynamic_values_bytes;
97 sigstack.ss_flags=0;
98 sigstack.ss_size = 32*SIGSTKSZ;
99 sigaltstack(&sigstack,0);
100 #endif
101 return 1; /* success */
104 int arch_os_thread_cleanup(struct thread *thread) {
105 #if defined(LISP_FEATURE_SB_THREAD)
106 int n = thread->tls_cookie;
108 /* Set the %%fs register back to 0 and free the ldt by setting it
109 * to NULL.
111 FSHOW_SIGNAL((stderr, "/ TLS: Freeing LDT %x\n", n));
113 __asm__ __volatile__ ("mov %0, %%fs" : : "r"(0));
114 thread_mutex_lock(&modify_ldt_lock);
115 i386_set_ldt(n, NULL, 1);
116 thread_mutex_unlock(&modify_ldt_lock);
117 #endif
118 return 1; /* success */
121 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
123 void sigill_handler(int signal, siginfo_t *siginfo, os_context_t *context);
124 void sigtrap_handler(int signal, siginfo_t *siginfo, os_context_t *context);
125 void memory_fault_handler(int signal, siginfo_t *siginfo,
126 os_context_t *context);
128 /* This executes in the faulting thread as part of the signal
129 * emulation. It is passed a context with the uc_mcontext field
130 * pointing to a valid block of memory. */
131 void build_fake_signal_context(os_context_t *context,
132 x86_thread_state32_t *thread_state,
133 x86_float_state32_t *float_state) {
134 thread_sigmask(0, NULL, &context->uc_sigmask);
135 context->uc_mcontext->SS = *thread_state;
136 context->uc_mcontext->FS = *float_state;
139 /* This executes in the faulting thread as part of the signal
140 * emulation. It is effectively the inverse operation from above. */
141 void update_thread_state_from_context(x86_thread_state32_t *thread_state,
142 x86_float_state32_t *float_state,
143 os_context_t *context) {
144 *thread_state = context->uc_mcontext->SS;
145 *float_state = context->uc_mcontext->FS;
146 thread_sigmask(SIG_SETMASK, &context->uc_sigmask, NULL);
149 /* Modify a context to push new data on its stack. */
150 void push_context(u32 data, x86_thread_state32_t *thread_state)
152 u32 *stack_pointer;
154 stack_pointer = (u32*) thread_state->ESP;
155 *(--stack_pointer) = data;
156 thread_state->ESP = (unsigned int) stack_pointer;
159 void align_context_stack(x86_thread_state32_t *thread_state)
161 /* 16byte align the stack (provided that the stack is, as it
162 * should be, 4byte aligned. */
163 while (thread_state->ESP & 15) push_context(0, thread_state);
166 /* Stack allocation starts with a context that has a mod-4 ESP value
167 * and needs to leave a context with a mod-16 ESP that will restore
168 * the old ESP value and other register state when activated. The
169 * first part of this is the recovery trampoline, which loads ESP from
170 * EBP, pops EBP, and returns. */
171 asm("_stack_allocation_recover: movl %ebp, %esp; popl %ebp; ret;");
173 void open_stack_allocation(x86_thread_state32_t *thread_state)
175 void stack_allocation_recover(void);
177 push_context(thread_state->EIP, thread_state);
178 push_context(thread_state->EBP, thread_state);
179 thread_state->EBP = thread_state->ESP;
180 thread_state->EIP = (unsigned int) stack_allocation_recover;
182 align_context_stack(thread_state);
185 /* Stack allocation of data starts with a context with a mod-16 ESP
186 * value and reserves some space on it by manipulating the ESP
187 * register. */
188 void *stack_allocate(x86_thread_state32_t *thread_state, size_t size)
190 /* round up size to 16byte multiple */
191 size = (size + 15) & -16;
193 thread_state->ESP = ((u32)thread_state->ESP) - size;
195 return (void *)thread_state->ESP;
198 /* Arranging to invoke a C function is tricky, as we have to assume
199 * cdecl calling conventions (caller removes args) and x86/darwin
200 * alignment requirements. The simplest way to arrange this,
201 * actually, is to open a new stack allocation.
202 * WARNING!!! THIS DOES NOT PRESERVE REGISTERS! */
203 void call_c_function_in_context(x86_thread_state32_t *thread_state,
204 void *function,
205 int nargs,
206 ...)
208 va_list ap;
209 int i;
210 u32 *stack_pointer;
212 /* Set up to restore stack on exit. */
213 open_stack_allocation(thread_state);
215 /* Have to keep stack 16byte aligned on x86/darwin. */
216 for (i = (3 & -nargs); i; i--) {
217 push_context(0, thread_state);
220 thread_state->ESP = ((u32)thread_state->ESP) - nargs * 4;
221 stack_pointer = (u32 *)thread_state->ESP;
223 va_start(ap, nargs);
224 for (i = 0; i < nargs; i++) {
225 //push_context(va_arg(ap, u32), thread_state);
226 stack_pointer[i] = va_arg(ap, u32);
228 va_end(ap);
230 push_context(thread_state->EIP, thread_state);
231 thread_state->EIP = (unsigned int) function;
234 void signal_emulation_wrapper(x86_thread_state32_t *thread_state,
235 x86_float_state32_t *float_state,
236 int signal,
237 siginfo_t *siginfo,
238 void (*handler)(int, siginfo_t *, void *))
241 os_context_t context;
242 _STRUCT_MCONTEXT32 regs;
244 context.uc_mcontext = &regs;
246 /* when BSD signals are fired, they mask they signals in sa_mask
247 which always seem to be the blockable_sigset, for us, so we
248 need to:
249 1) save the current sigmask
250 2) block blockable signals
251 3) call the signal handler
252 4) restore the sigmask */
253 build_fake_signal_context(&context, thread_state, float_state);
255 block_blockable_signals(0);
257 handler(signal, siginfo, &context);
259 update_thread_state_from_context(thread_state, float_state, &context);
261 /* Trap to restore the signal context. */
262 asm volatile (".long 0xffff0b0f"
263 : : "a" (thread_state), "c" (float_state));
266 /* Convenience wrapper for the above */
267 void call_handler_on_thread(mach_port_t thread,
268 x86_thread_state32_t *thread_state,
269 int signal,
270 siginfo_t *siginfo,
271 void (*handler)(int, siginfo_t *, os_context_t *))
273 x86_thread_state32_t new_state;
274 x86_thread_state32_t *save_thread_state;
275 x86_float_state32_t *save_float_state;
276 mach_msg_type_number_t state_count;
277 siginfo_t *save_siginfo;
278 kern_return_t ret;
279 /* Initialize the new state */
280 new_state = *thread_state;
281 open_stack_allocation(&new_state);
282 stack_allocate(&new_state, 256);
283 /* Save old state */
284 save_thread_state = (x86_thread_state32_t *)stack_allocate(&new_state, sizeof(*save_thread_state));
285 *save_thread_state = *thread_state;
286 /* Save float state */
287 save_float_state = (x86_float_state32_t *)stack_allocate(&new_state, sizeof(*save_float_state));
288 state_count = x86_FLOAT_STATE32_COUNT;
289 if ((ret = thread_get_state(thread,
290 x86_FLOAT_STATE32,
291 (thread_state_t)save_float_state,
292 &state_count)) != KERN_SUCCESS)
293 lose("thread_get_state (x86_THREAD_STATE32) failed %d\n", ret);
294 /* Set up siginfo */
295 save_siginfo = stack_allocate(&new_state, sizeof(*siginfo));
296 if (siginfo == NULL)
297 save_siginfo = siginfo;
298 else
299 *save_siginfo = *siginfo;
300 /* Prepare to call */
301 call_c_function_in_context(&new_state,
302 signal_emulation_wrapper,
304 save_thread_state,
305 save_float_state,
306 signal,
307 save_siginfo,
308 handler);
309 /* Update the thread state */
310 state_count = x86_THREAD_STATE32_COUNT;
311 if ((ret = thread_set_state(thread,
312 x86_THREAD_STATE32,
313 (thread_state_t)&new_state,
314 state_count)) != KERN_SUCCESS)
315 lose("thread_set_state (x86_FLOAT_STATE32) failed %d\n", ret);
319 #if defined DUMP_CONTEXT
320 void dump_context(x86_thread_state32_t *thread_state)
322 int i;
323 u32 *stack_pointer;
325 printf("eax: %08lx ecx: %08lx edx: %08lx ebx: %08lx\n",
326 thread_state->EAX, thread_state->ECX, thread_state->EDX, thread_state->EAX);
327 printf("esp: %08lx ebp: %08lx esi: %08lx edi: %08lx\n",
328 thread_state->ESP, thread_state->EBP, thread_state->ESI, thread_state->EDI);
329 printf("eip: %08lx eflags: %08lx\n",
330 thread_state->EIP, thread_state->EFLAGS);
331 printf("cs: %04hx ds: %04hx es: %04hx "
332 "ss: %04hx fs: %04hx gs: %04hx\n",
333 thread_state->CS,
334 thread_state->DS,
335 thread_state->ES,
336 thread_state->SS,
337 thread_state->FS,
338 thread_state->GS);
340 stack_pointer = (u32 *)thread_state->ESP;
341 for (i = 0; i < 48; i+=4) {
342 printf("%08x: %08x %08x %08x %08x\n",
343 thread_state->ESP + (i * 4),
344 stack_pointer[i],
345 stack_pointer[i+1],
346 stack_pointer[i+2],
347 stack_pointer[i+3]);
350 #endif
352 void
353 control_stack_exhausted_handler(int signal, siginfo_t *siginfo,
354 os_context_t *context) {
355 extern void unblock_signals_in_context_and_maybe_warn(os_context_t*);
356 unblock_signals_in_context_and_maybe_warn(context);
357 arrange_return_to_lisp_function
358 (context, StaticSymbolFunction(CONTROL_STACK_EXHAUSTED_ERROR));
361 void
362 undefined_alien_handler(int signal, siginfo_t *siginfo, os_context_t *context) {
363 arrange_return_to_lisp_function
364 (context, StaticSymbolFunction(UNDEFINED_ALIEN_VARIABLE_ERROR));
367 kern_return_t
368 catch_exception_raise(mach_port_t exception_port,
369 mach_port_t thread,
370 mach_port_t task,
371 exception_type_t exception,
372 exception_data_t code_vector,
373 mach_msg_type_number_t code_count)
375 x86_thread_state32_t thread_state;
376 mach_msg_type_number_t state_count;
377 void *addr = NULL;
378 int signal = 0;
379 void (*handler)(int, siginfo_t *, os_context_t *) = NULL;
380 siginfo_t siginfo;
381 kern_return_t ret, dealloc_ret;
383 struct thread *th;
385 FSHOW((stderr,"/entering catch_exception_raise with exception: %d\n", exception));
387 if (mach_port_get_context(mach_task_self(), exception_port, (mach_vm_address_t *)&th)
388 != KERN_SUCCESS) {
389 lose("Can't find the thread for an exception %p", exception_port);
392 /* Get state and info */
393 state_count = x86_THREAD_STATE32_COUNT;
394 if ((ret = thread_get_state(thread,
395 x86_THREAD_STATE32,
396 (thread_state_t)&thread_state,
397 &state_count)) != KERN_SUCCESS)
398 lose("thread_get_state (x86_THREAD_STATE32) failed %d\n", ret);
399 switch (exception) {
400 case EXC_BAD_ACCESS:
401 signal = SIGBUS;
402 /* Check if write protection fault */
403 if ((code_vector[0] & OS_VM_PROT_ALL) == 0) {
404 ret = KERN_INVALID_RIGHT;
405 break;
407 addr = (void*)code_vector[1];
408 /* Undefined alien */
409 if (os_trunc_to_page(addr) == undefined_alien_address) {
410 handler = undefined_alien_handler;
411 break;
413 /* At stack guard */
414 if (os_trunc_to_page(addr) == CONTROL_STACK_GUARD_PAGE(th)) {
415 lower_thread_control_stack_guard_page(th);
416 handler = control_stack_exhausted_handler;
417 break;
419 /* Return from stack guard */
420 if (os_trunc_to_page(addr) == CONTROL_STACK_RETURN_GUARD_PAGE(th)) {
421 reset_thread_control_stack_guard_page(th);
422 break;
424 /* Regular memory fault */
425 handler = memory_fault_handler;
426 break;
427 case EXC_BAD_INSTRUCTION:
428 signal = SIGTRAP;
429 /* Check if illegal instruction trap */
430 if (code_vector[0] != EXC_I386_INVOP) {
431 ret = KERN_INVALID_RIGHT;
432 break;
434 /* Check if UD2 instruction */
435 if (*(unsigned short *)thread_state.EIP != 0x0b0f) {
436 /* KLUDGE: There are two ways we could get here:
437 * 1) We're executing data and we've hit some truly
438 * illegal opcode, of which there are a few, see
439 * Intel 64 and IA-32 Architectures
440 * Sofware Developer's Manual
441 * Volume 3A page 5-34)
442 * 2) The kernel started an unrelated signal handler
443 * before we got a chance to run. The context that
444 * caused the exception is saved in a stack frame
445 * somewhere down below.
446 * In either case we rely on the exception to retrigger,
447 * eventually bailing out if we're spinning on case 2).
449 static mach_port_t last_thread;
450 static unsigned int last_eip;
451 if (last_thread == thread && last_eip == thread_state.EIP)
452 ret = KERN_INVALID_RIGHT;
453 else
454 ret = KERN_SUCCESS;
455 last_thread = thread;
456 last_eip = thread_state.EIP;
457 break;
459 /* Skip the trap code */
460 thread_state.EIP += 2;
461 /* Return from handler? */
462 if (*(unsigned short *)thread_state.EIP == 0xffff) {
463 if ((ret = thread_set_state(thread,
464 x86_THREAD_STATE32,
465 (thread_state_t)thread_state.EAX,
466 x86_THREAD_STATE32_COUNT)) != KERN_SUCCESS)
467 lose("thread_set_state (x86_THREAD_STATE32) failed %d\n", ret);
468 if ((ret = thread_set_state(thread,
469 x86_FLOAT_STATE32,
470 (thread_state_t)thread_state.ECX,
471 x86_FLOAT_STATE32_COUNT)) != KERN_SUCCESS)
472 lose("thread_set_state (x86_FLOAT_STATE32) failed %d\n", ret);
473 break;
475 /* Trap call */
476 handler = sigtrap_handler;
477 break;
478 default:
479 ret = KERN_INVALID_RIGHT;
481 /* Call handler */
482 if (handler != 0) {
483 siginfo.si_signo = signal;
484 siginfo.si_addr = addr;
485 call_handler_on_thread(thread, &thread_state, signal, &siginfo, handler);
488 dealloc_ret = mach_port_deallocate (mach_task_self(), thread);
489 if (dealloc_ret) {
490 lose("mach_port_deallocate (thread) failed with return_code %d\n", dealloc_ret);
493 dealloc_ret = mach_port_deallocate (mach_task_self(), task);
494 if (dealloc_ret) {
495 lose("mach_port_deallocate (task) failed with return_code %d\n", dealloc_ret);
498 return ret;
501 void
502 os_restore_fp_control(os_context_t *context)
504 /* KLUDGE: The x87 FPU control word is some nasty bitfield struct
505 * thing. Rather than deal with that, just grab it as a 16-bit
506 * integer. */
507 unsigned short fpu_control_word =
508 *((unsigned short *)&context->uc_mcontext->FS.FPU_FCW);
509 /* reset exception flags and restore control flags on x87 FPU */
510 asm ("fldcw %0" : : "m" (fpu_control_word));
513 #endif