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