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