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