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