1.0.3.16: experimental x86-64/darwin suport
[sbcl.git] / src / runtime / x86-64-arch.c
1 /*
2  * This software is part of the SBCL system. See the README file for
3  * more information.
4  *
5  * This software is derived from the CMU CL system, which was
6  * written at Carnegie Mellon University and released into the
7  * public domain. The software is in the public domain and is
8  * provided with absolutely no warranty. See the COPYING and CREDITS
9  * files for more information.
10  */
11
12 #include <stdio.h>
13
14 #include "sbcl.h"
15 #include "runtime.h"
16 #include "globals.h"
17 #include "validate.h"
18 #include "os.h"
19 #include "sbcl.h"
20 #include "arch.h"
21 #include "lispregs.h"
22 #include "signal.h"
23 #include "alloc.h"
24 #include "interrupt.h"
25 #include "interr.h"
26 #include "breakpoint.h"
27 #include "thread.h"
28
29 #include "genesis/static-symbols.h"
30 #include "genesis/symbol.h"
31
32 #define BREAKPOINT_INST 0xcc    /* INT3 */
33
34 unsigned long fast_random_state = 1;
35
36 void arch_init(void)
37 {}
38
39 os_vm_address_t
40 arch_get_bad_addr(int sig, siginfo_t *code, os_context_t *context)
41 {
42     return (os_vm_address_t)code->si_addr;
43 }
44
45 \f
46 /*
47  * hacking signal contexts
48  *
49  * (This depends both on architecture, which determines what we might
50  * want to get to, and on OS, which determines how we get to it.)
51  */
52
53 os_context_register_t *
54 context_eflags_addr(os_context_t *context)
55 {
56 #if defined __linux__
57     /* KLUDGE: As of kernel 2.2.14 on Red Hat 6.2, there's code in the
58      * <sys/ucontext.h> file to define symbolic names for offsets into
59      * gregs[], but it's conditional on __USE_GNU and not defined, so
60      * we need to do this nasty absolute index magic number thing
61      * instead. */
62     return &context->uc_mcontext.gregs[17];
63 #elif defined __FreeBSD__
64     return &context->uc_mcontext.mc_rflags;
65 #elif defined LISP_FEATURE_DARWIN
66     return &context->uc_mcontext->ss.rflags;
67 #elif defined __OpenBSD__
68     return &context->sc_eflags;
69 #else
70 #error unsupported OS
71 #endif
72 }
73 \f
74 void arch_skip_instruction(os_context_t *context)
75 {
76     /* Assuming we get here via an INT3 xxx instruction, the PC now
77      * points to the interrupt code (a Lisp value) so we just move
78      * past it. Skip the code; after that, if the code is an
79      * error-trap or cerror-trap then skip the data bytes that follow. */
80
81     int vlen;
82     long code;
83
84
85     /* Get and skip the Lisp interrupt code. */
86     code = *(char*)(*os_context_pc_addr(context))++;
87     switch (code)
88         {
89         case trap_Error:
90         case trap_Cerror:
91             /* Lisp error arg vector length */
92             vlen = *(char*)(*os_context_pc_addr(context))++;
93             /* Skip Lisp error arg data bytes. */
94             while (vlen-- > 0) {
95                 ++*os_context_pc_addr(context);
96             }
97             break;
98
99         case trap_Breakpoint:           /* not tested */
100         case trap_FunEndBreakpoint: /* not tested */
101             break;
102
103         case trap_PendingInterrupt:
104         case trap_Halt:
105         case trap_SingleStepAround:
106         case trap_SingleStepBefore:
107             /* only needed to skip the Code */
108             break;
109
110         default:
111             fprintf(stderr,"[arch_skip_inst invalid code %ld\n]\n",code);
112             break;
113         }
114
115     FSHOW((stderr,
116            "/[arch_skip_inst resuming at %x]\n",
117            *os_context_pc_addr(context)));
118 }
119
120 unsigned char *
121 arch_internal_error_arguments(os_context_t *context)
122 {
123     return 1 + (unsigned char *)(*os_context_pc_addr(context));
124 }
125
126 boolean
127 arch_pseudo_atomic_atomic(os_context_t *context)
128 {
129     return get_pseudo_atomic_atomic(arch_os_get_current_thread());
130 }
131
132 void
133 arch_set_pseudo_atomic_interrupted(os_context_t *context)
134 {
135     struct thread *thread = arch_os_get_current_thread();
136     set_pseudo_atomic_interrupted(thread);
137 }
138
139 void
140 arch_clear_pseudo_atomic_interrupted(os_context_t *context)
141 {
142     struct thread *thread = arch_os_get_current_thread();
143     clear_pseudo_atomic_interrupted(thread);
144 }
145 \f
146 /*
147  * This stuff seems to get called for TRACE and debug activity.
148  */
149
150 unsigned int
151 arch_install_breakpoint(void *pc)
152 {
153     unsigned int result = *(unsigned int*)pc;
154
155     *(char*)pc = BREAKPOINT_INST;               /* x86 INT3       */
156     *((char*)pc+1) = trap_Breakpoint;           /* Lisp trap code */
157
158     return result;
159 }
160
161 void
162 arch_remove_breakpoint(void *pc, unsigned int orig_inst)
163 {
164     *((char *)pc) = orig_inst & 0xff;
165     *((char *)pc + 1) = (orig_inst & 0xff00) >> 8;
166 }
167 \f
168 /* When single stepping, single_stepping holds the original instruction
169  * PC location. */
170 unsigned int *single_stepping = NULL;
171 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
172 unsigned int  single_step_save1;
173 unsigned int  single_step_save2;
174 unsigned int  single_step_save3;
175 #endif
176
177 void
178 arch_do_displaced_inst(os_context_t *context, unsigned int orig_inst)
179 {
180     unsigned int *pc = (unsigned int*)(*os_context_pc_addr(context));
181
182     /* Put the original instruction back. */
183     *((char *)pc) = orig_inst & 0xff;
184     *((char *)pc + 1) = (orig_inst & 0xff00) >> 8;
185
186 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
187     /* Install helper instructions for the single step:
188      * pushf; or [esp],0x100; popf. */
189     single_step_save1 = *(pc-3);
190     single_step_save2 = *(pc-2);
191     single_step_save3 = *(pc-1);
192     *(pc-3) = 0x9c909090;
193     *(pc-2) = 0x00240c81;
194     *(pc-1) = 0x9d000001;
195 #else
196     *context_eflags_addr(context) |= 0x100;
197 #endif
198
199     single_stepping = pc;
200
201 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
202     *os_context_pc_addr(context) = (os_context_register_t)((char *)pc - 9);
203 #endif
204 }
205
206 \f
207 void
208 sigtrap_handler(int signal, siginfo_t *info, void *void_context)
209 {
210     int code = info->si_code;
211     os_context_t *context = (os_context_t*)void_context;
212     unsigned int trap;
213
214     if (single_stepping && (signal==SIGTRAP))
215     {
216 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
217         /* Un-install single step helper instructions. */
218         *(single_stepping-3) = single_step_save1;
219         *(single_stepping-2) = single_step_save2;
220         *(single_stepping-1) = single_step_save3;
221 #else
222         *context_eflags_addr(context) ^= 0x100;
223 #endif
224         /* Re-install the breakpoint if possible. */
225         if ((char *)*os_context_pc_addr(context) ==
226             (char *)single_stepping + 1) {
227             fprintf(stderr, "warning: couldn't reinstall breakpoint\n");
228         } else {
229             *((char *)single_stepping) = BREAKPOINT_INST;       /* x86 INT3 */
230             *((char *)single_stepping+1) = trap_Breakpoint;
231         }
232
233         single_stepping = NULL;
234         return;
235     }
236
237     /* This is just for info in case the monitor wants to print an
238      * approximation. */
239     current_control_stack_pointer =
240         (lispobj *)*os_context_sp_addr(context);
241
242     /* FIXME: CMUCL puts the float control restoration code here.
243        Thus, it seems to me that single-stepping won't restore the
244        float control.  Since SBCL currently doesn't support
245        single-stepping (as far as I can tell) this is somewhat moot,
246        but it might be worth either moving this code up or deleting
247        the single-stepping code entirely.  -- CSR, 2002-07-15 */
248 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
249     os_restore_fp_control(context);
250 #endif
251
252     /* On entry %eip points just after the INT3 byte and aims at the
253      * 'kind' value (eg trap_Cerror). For error-trap and Cerror-trap a
254      * number of bytes will follow, the first is the length of the byte
255      * arguments to follow. */
256     trap = *(unsigned char *)(*os_context_pc_addr(context));
257     switch (trap) {
258
259     case trap_PendingInterrupt:
260         FSHOW((stderr, "/<trap pending interrupt>\n"));
261         arch_skip_instruction(context);
262         interrupt_handle_pending(context);
263         break;
264
265     case trap_Halt:
266         /* Note: the old CMU CL code tried to save FPU state
267          * here, and restore it after we do our thing, but there
268          * seems to be no point in doing that, since we're just
269          * going to lose(..) anyway. */
270         fake_foreign_function_call(context);
271         lose("%%PRIMITIVE HALT called; the party is over.\n");
272
273     case trap_Error:
274     case trap_Cerror:
275         FSHOW((stderr, "<trap error/cerror %d>\n", trap));
276         interrupt_internal_error(signal, info, context, trap==trap_Cerror);
277         break;
278
279     case trap_Breakpoint:
280         --*os_context_pc_addr(context);
281         handle_breakpoint(signal, info, context);
282         break;
283
284     case trap_FunEndBreakpoint:
285         --*os_context_pc_addr(context);
286         *os_context_pc_addr(context) =
287             (unsigned long)handle_fun_end_breakpoint(signal, info, context);
288         break;
289
290     case trap_SingleStepAround:
291     case trap_SingleStepBefore:
292         arch_skip_instruction(context);
293         /* On x86-64 the fdefn / function is always in RAX, so we pass
294          * 0 as the register_offset. */
295         handle_single_step_trap(context, trap, 0);
296         break;
297
298     default:
299         FSHOW((stderr,"/[C--trap default %d %d %x]\n",
300                signal, code, context));
301         interrupt_handle_now(signal, info, context);
302         break;
303     }
304 }
305
306 void
307 sigill_handler(int signal, siginfo_t *siginfo, void *void_context) {
308     os_context_t *context = (os_context_t*)void_context;
309
310     /* Triggering SIGTRAP using int3 is unreliable on OS X/x86, so
311      * we need to use illegal instructions for traps.
312      */
313 #if defined(LISP_FEATURE_DARWIN) && !defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
314     if (*((unsigned short *)*os_context_pc_addr(context)) == 0x0b0f) {
315         *os_context_pc_addr(context) += 2;
316         return sigtrap_handler(signal, siginfo, void_context);
317     }
318 #endif
319
320     fake_foreign_function_call(context);
321     lose("fake_foreign_function_call fell through");
322 }
323
324 #ifdef X86_64_SIGFPE_FIXUP
325 #define MXCSR_IE (0x01)         /* Invalid Operation */
326 #define MXCSR_DE (0x02)         /* Denormal */
327 #define MXCSR_ZE (0x04)         /* Devide-by-Zero */
328 #define MXCSR_OE (0x08)         /* Overflow */
329 #define MXCSR_UE (0x10)         /* Underflow */
330 #define MXCSR_PE (0x20)         /* Precision */
331
332 static inline int
333 mxcsr_to_code(unsigned int mxcsr)
334 {
335     /* Extract unmasked exception bits. */
336     mxcsr &= ~(mxcsr >> 7) & 0x3F;
337
338     /* This order is defined at "Intel 64 and IA-32 Architectures
339      * Software Developerfs Manual" Volume 1: "Basic Architecture",
340      * 4.9.2 "Floating-Point Exception Priority". */
341     if (mxcsr & MXCSR_IE)
342         return FPE_FLTINV;
343     else if (mxcsr & MXCSR_ZE)
344         return FPE_FLTDIV;
345     else if (mxcsr & MXCSR_DE)
346         return FPE_FLTUND;
347     else if (mxcsr & MXCSR_OE)
348         return FPE_FLTOVF;
349     else if (mxcsr & MXCSR_UE)
350         return FPE_FLTUND;
351     else if (mxcsr & MXCSR_PE)
352         return FPE_FLTRES;
353
354     return 0;
355 }
356
357 static void
358 sigfpe_handler(int signal, siginfo_t *siginfo, void *void_context)
359 {
360     os_context_t *context = arch_os_get_context(&void_context);
361     unsigned int *mxcsr = arch_os_context_mxcsr_addr(context);
362
363     if (siginfo->si_code == 0) { /* XMM exception */
364         siginfo->si_code = mxcsr_to_code(*mxcsr);
365
366         /* Clear sticky exception flag. */
367         *mxcsr &= ~0x3F;
368     }
369
370     interrupt_handle_now(signal, siginfo, context);
371 }
372 #endif
373
374 void
375 arch_install_interrupt_handlers()
376 {
377     SHOW("entering arch_install_interrupt_handlers()");
378
379     /* Note: The old CMU CL code here used sigtrap_handler() to handle
380      * SIGILL as well as SIGTRAP. I couldn't see any reason to do
381      * things that way. So, I changed to separate handlers when
382      * debugging a problem on OpenBSD, where SBCL wasn't catching
383      * SIGILL properly, but was instead letting the process be
384      * terminated with an "Illegal instruction" output. If this change
385      * turns out to break something (maybe breakpoint handling on some
386      * OS I haven't tested on?) and we have to go back to the old CMU
387      * CL way, I hope there will at least be a comment to explain
388      * why.. -- WHN 2001-06-07 */
389 #if !defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
390     undoably_install_low_level_interrupt_handler(SIGILL , sigill_handler);
391     undoably_install_low_level_interrupt_handler(SIGTRAP, sigtrap_handler);
392 #endif
393
394 #ifdef X86_64_SIGFPE_FIXUP
395     undoably_install_low_level_interrupt_handler(SIGFPE, sigfpe_handler);
396 #endif
397
398     SHOW("returning from arch_install_interrupt_handlers()");
399 }
400 \f
401 /* This is implemented in assembly language and called from C: */
402 extern lispobj
403 call_into_lisp(lispobj fun, lispobj *args, int nargs);
404
405 /* These functions are an interface to the Lisp call-in facility.
406  * Since this is C we can know nothing about the calling environment.
407  * The control stack might be the C stack if called from the monitor
408  * or the Lisp stack if called as a result of an interrupt or maybe
409  * even a separate stack. The args are most likely on that stack but
410  * could be in registers depending on what the compiler likes. So we
411  * copy the args into a portable vector and let the assembly language
412  * call-in function figure it out. */
413
414 lispobj
415 funcall0(lispobj function)
416 {
417     lispobj *args = NULL;
418
419     FSHOW((stderr, "/entering funcall0(0x%lx)\n", (long)function));
420     return call_into_lisp(function, args, 0);
421 }
422 lispobj
423 funcall1(lispobj function, lispobj arg0)
424 {
425     lispobj args[1];
426     args[0] = arg0;
427     return call_into_lisp(function, args, 1);
428 }
429 lispobj
430 funcall2(lispobj function, lispobj arg0, lispobj arg1)
431 {
432     lispobj args[2];
433     args[0] = arg0;
434     args[1] = arg1;
435     return call_into_lisp(function, args, 2);
436 }
437 lispobj
438 funcall3(lispobj function, lispobj arg0, lispobj arg1, lispobj arg2)
439 {
440     lispobj args[3];
441     args[0] = arg0;
442     args[1] = arg1;
443     args[2] = arg2;
444     return call_into_lisp(function, args, 3);
445 }
446
447
448 #ifdef LISP_FEATURE_LINKAGE_TABLE
449 /* FIXME: It might be cleaner to generate these from the lisp side of
450  * things.
451  */
452
453 void
454 arch_write_linkage_table_jmp(char * reloc, void * fun)
455 {
456     unsigned long addr = (unsigned long) fun;
457     int i;
458
459     *reloc++ = 0xFF; /* Opcode for near jump to absolute reg/mem64. */
460     *reloc++ = 0x25; /* ModRM #b00 100 101, i.e. RIP-relative. */
461     *reloc++ = 0x00; /* 32-bit displacement field = 0 */
462     *reloc++ = 0x00; /* ... */
463     *reloc++ = 0x00; /* ... */
464     *reloc++ = 0x00; /* ... */
465
466     for (i = 0; i < 8; i++) {
467         *reloc++ = addr & 0xff;
468         addr >>= 8;
469     }
470
471     /* write a nop for good measure. */
472     *reloc = 0x90;
473 }
474
475 void
476 arch_write_linkage_table_ref(void * reloc, void * data)
477 {
478     *(unsigned long *)reloc = (unsigned long)data;
479 }
480
481 #endif
482
483 /* These setup and check *both* the sse2 and x87 FPUs. While lisp code
484    only uses the sse2 FPU, other code (such as libc) may use the x87 FPU.
485  */
486
487 unsigned int
488 arch_get_fp_modes()
489 {
490     unsigned int temp;
491     unsigned int result;
492     /* return the x87 exception flags ored in with the sse2
493      * control+status flags */
494     asm ("fnstsw %0" : "=m" (temp));
495     result = temp;
496     result &= 0x3F;
497     asm ("stmxcsr %0" : "=m" (temp));
498     result |= temp;
499     /* flip exception mask bits */
500     return result ^ (0x3F << 7);
501 }
502
503 struct fpenv
504 {
505     unsigned short cw;
506     unsigned short unused1;
507     unsigned short sw;
508     unsigned short unused2;
509     unsigned int other_regs[5];
510 };
511
512 void
513 arch_set_fp_modes(unsigned int mxcsr)
514 {
515     struct fpenv f_env;
516     unsigned int temp;
517
518     /* turn trap enable bits into exception mask */
519     mxcsr ^= 0x3F << 7;
520
521     /* set x87 modes */
522     asm ("fnstenv %0" : "=m" (f_env));
523     /* set control word: always long double precision
524      * get traps and rounding from mxcsr word */
525     f_env.cw = 0x300 | ((mxcsr >> 7) & 0x3F) | (((mxcsr >> 13) & 0x3) << 10);
526     /* set status word: only override exception flags, from mxcsr */
527     f_env.sw &= ~0x3F;
528     f_env.sw |= (mxcsr & 0x3F);
529
530     asm ("fldenv %0" : : "m" (f_env));
531
532     /* now, simply, load up the mxcsr register */
533     temp = mxcsr;
534     asm ("ldmxcsr %0" : : "m" (temp));
535 }