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