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