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