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