4540142a9b8537cf1d11968eca28ffe0df669d44
[sbcl.git] / src / runtime / x86-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 "arch.h"
20 #include "lispregs.h"
21 #include "signal.h"
22 #include "alloc.h"
23 #include "interrupt.h"
24 #include "interr.h"
25 #include "breakpoint.h"
26 #include "thread.h"
27
28 #include "genesis/static-symbols.h"
29 #include "genesis/symbol.h"
30
31 #define BREAKPOINT_INST 0xcc    /* INT3 */
32
33 unsigned long fast_random_state = 1;
34
35 void arch_init(void)
36 {}
37
38 #ifndef LISP_FEATURE_WIN32
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 #endif
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__ || defined __sun
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[16];
64 #elif defined __FreeBSD__
65     return &context->uc_mcontext.mc_eflags;
66 #elif defined __OpenBSD__
67     return &context->sc_eflags;
68 #elif defined LISP_FEATURE_DARWIN
69     return &context->uc_mcontext->ss.eflags;
70 #elif defined __NetBSD__
71     return &(context->uc_mcontext.__gregs[_REG_EFL]);
72 #elif defined LISP_FEATURE_WIN32
73     return (int *)&context->EFlags;
74 #else
75 #error unsupported OS
76 #endif
77 }
78 \f
79 void arch_skip_instruction(os_context_t *context)
80 {
81     /* Assuming we get here via an INT3 xxx instruction, the PC now
82      * points to the interrupt code (a Lisp value) so we just move
83      * past it. Skip the code; after that, if the code is an
84      * error-trap or cerror-trap then skip the data bytes that follow. */
85
86     int vlen;
87     int code;
88
89
90     /* Get and skip the Lisp interrupt code. */
91     code = *(char*)(*os_context_pc_addr(context))++;
92     switch (code)
93         {
94         case trap_Error:
95         case trap_Cerror:
96             /* Lisp error arg vector length */
97             vlen = *(char*)(*os_context_pc_addr(context))++;
98             /* Skip Lisp error arg data bytes. */
99             while (vlen-- > 0) {
100                 ++*os_context_pc_addr(context);
101             }
102             break;
103
104         case trap_Breakpoint:           /* not tested */
105         case trap_FunEndBreakpoint: /* not tested */
106             break;
107
108         case trap_PendingInterrupt:
109         case trap_Halt:
110         case trap_SingleStepAround:
111         case trap_SingleStepBefore:
112             /* only needed to skip the Code */
113             break;
114
115         default:
116             fprintf(stderr,"[arch_skip_inst invalid code %d\n]\n",code);
117             break;
118         }
119
120     FSHOW((stderr,
121            "/[arch_skip_inst resuming at %x]\n",
122            *os_context_pc_addr(context)));
123 }
124
125 unsigned char *
126 arch_internal_error_arguments(os_context_t *context)
127 {
128     return 1 + (unsigned char *)(*os_context_pc_addr(context));
129 }
130
131 boolean
132 arch_pseudo_atomic_atomic(os_context_t *context)
133 {
134     return get_pseudo_atomic_atomic(arch_os_get_current_thread());
135 }
136
137 void
138 arch_set_pseudo_atomic_interrupted(os_context_t *context)
139 {
140     struct thread *thread = arch_os_get_current_thread();
141     set_pseudo_atomic_interrupted(thread);
142 }
143
144 void
145 arch_clear_pseudo_atomic_interrupted(os_context_t *context)
146 {
147     struct thread *thread = arch_os_get_current_thread();
148     clear_pseudo_atomic_interrupted(thread);
149 }
150 \f
151 /*
152  * This stuff seems to get called for TRACE and debug activity.
153  */
154
155 unsigned int
156 arch_install_breakpoint(void *pc)
157 {
158     unsigned int result = *(unsigned int*)pc;
159
160     *(char*)pc = BREAKPOINT_INST;               /* x86 INT3       */
161     *((char*)pc+1) = trap_Breakpoint;           /* Lisp trap code */
162
163     return result;
164 }
165
166 void
167 arch_remove_breakpoint(void *pc, unsigned int orig_inst)
168 {
169     *((char *)pc) = orig_inst & 0xff;
170     *((char *)pc + 1) = (orig_inst & 0xff00) >> 8;
171 }
172 \f
173 /* When single stepping, single_stepping holds the original instruction
174  * PC location. */
175 unsigned int *single_stepping = NULL;
176 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
177 unsigned int  single_step_save1;
178 unsigned int  single_step_save2;
179 unsigned int  single_step_save3;
180 #endif
181
182 void
183 arch_do_displaced_inst(os_context_t *context, unsigned int orig_inst)
184 {
185     unsigned int *pc = (unsigned int*)(*os_context_pc_addr(context));
186
187     /* Put the original instruction back. */
188     *((char *)pc) = orig_inst & 0xff;
189     *((char *)pc + 1) = (orig_inst & 0xff00) >> 8;
190
191 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
192     /* Install helper instructions for the single step:
193      * pushf; or [esp],0x100; popf. */
194     single_step_save1 = *(pc-3);
195     single_step_save2 = *(pc-2);
196     single_step_save3 = *(pc-1);
197     *(pc-3) = 0x9c909090;
198     *(pc-2) = 0x00240c81;
199     *(pc-1) = 0x9d000001;
200 #else
201     *context_eflags_addr(context) |= 0x100;
202 #endif
203
204     single_stepping = pc;
205
206 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
207     *os_context_pc_addr(context) = (char *)pc - 9;
208 #endif
209 }
210 \f
211 void
212 sigtrap_handler(int signal, siginfo_t *info, void *void_context)
213 {
214     os_context_t *context = (os_context_t*)void_context;
215     unsigned int trap;
216
217 #ifndef LISP_FEATURE_WIN32
218     if (single_stepping && (signal==SIGTRAP))
219     {
220         /* fprintf(stderr,"* single step trap %x\n", single_stepping); */
221
222 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
223         /* Un-install single step helper instructions. */
224         *(single_stepping-3) = single_step_save1;
225         *(single_stepping-2) = single_step_save2;
226         *(single_stepping-1) = single_step_save3;
227 #else
228         *context_eflags_addr(context) &= ~0x100;
229 #endif
230         /* Re-install the breakpoint if possible. */
231         if (*os_context_pc_addr(context) == (int)single_stepping + 1) {
232             fprintf(stderr, "warning: couldn't reinstall breakpoint\n");
233         } else {
234             *((char *)single_stepping) = BREAKPOINT_INST;       /* x86 INT3 */
235             *((char *)single_stepping+1) = trap_Breakpoint;
236         }
237
238         single_stepping = NULL;
239         return;
240     }
241 #endif
242
243     /* This is just for info in case the monitor wants to print an
244      * approximation. */
245     current_control_stack_pointer =
246         (lispobj *)*os_context_sp_addr(context);
247
248     /* FIXME: CMUCL puts the float control restoration code here.
249        Thus, it seems to me that single-stepping won't restore the
250        float control.  Since SBCL currently doesn't support
251        single-stepping (as far as I can tell) this is somewhat moot,
252        but it might be worth either moving this code up or deleting
253        the single-stepping code entirely.  -- CSR, 2002-07-15 */
254 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
255     os_restore_fp_control(context);
256 #endif
257
258
259 #ifdef LISP_FEATURE_SUNOS
260     /* For some reason the breakpoints that :ENCAPSULATE NIL tracing sets up
261      * cause a trace trap (i.e. processor single-stepping trap) on the following
262      * instruction on Solaris 10/x86. -- JES, 2006-04-07
263      */
264     if (info->si_code == TRAP_TRACE) {
265         lose("foo");
266         return;
267     }
268 #endif
269
270     /* On entry %eip points just after the INT3 byte and aims at the
271      * 'kind' value (eg trap_Cerror). For error-trap and Cerror-trap a
272      * number of bytes will follow, the first is the length of the byte
273      * arguments to follow. */
274     trap = *(unsigned char *)(*os_context_pc_addr(context));
275     /* FSHOW((stderr, "/<sigtrap trap %d at pc_addr: %p>\n", trap, *os_context_pc_addr(context))); */
276     switch (trap) {
277
278     case trap_PendingInterrupt:
279         FSHOW((stderr, "/<trap pending interrupt>\n"));
280         arch_skip_instruction(context);
281         interrupt_handle_pending(context);
282         break;
283
284     case trap_Halt:
285         /* Note: the old CMU CL code tried to save FPU state
286          * here, and restore it after we do our thing, but there
287          * seems to be no point in doing that, since we're just
288          * going to lose(..) anyway. */
289         fake_foreign_function_call(context);
290         lose("%%PRIMITIVE HALT called; the party is over.\n");
291
292     case trap_Error:
293     case trap_Cerror:
294         FSHOW((stderr, "<trap error/cerror %d>\n", trap));
295         interrupt_internal_error(signal, info, context, trap==trap_Cerror);
296         break;
297
298     case trap_Breakpoint:
299         --*os_context_pc_addr(context);
300         handle_breakpoint(signal, info, context);
301         break;
302
303     case trap_FunEndBreakpoint:
304         --*os_context_pc_addr(context);
305         *os_context_pc_addr(context) =
306             (int)handle_fun_end_breakpoint(signal, info, context);
307         break;
308
309     case trap_SingleStepAround:
310     case trap_SingleStepBefore:
311         arch_skip_instruction(context);
312         /* On x86 the fdefn / function is always in EAX, so we pass 0
313          * as the register_offset. */
314         handle_single_step_trap(context, trap, 0);
315         break;
316
317     default:
318         FSHOW((stderr,"/[C--trap default %d %d %x]\n",
319                signal, trap, context));
320         interrupt_handle_now(signal, info, context);
321         break;
322     }
323 }
324
325 static void
326 sigill_handler(int signal, siginfo_t *siginfo, void *void_context) {
327     os_context_t *context = (os_context_t*)void_context;
328
329     /* Triggering SIGTRAP using int3 is unreliable on OS X/x86, so
330      * we need to use illegal instructions for traps.
331      */
332 #if defined(LISP_FEATURE_DARWIN)
333     if (*((unsigned short *)*os_context_pc_addr(context)) == 0x0b0f) {
334         *os_context_pc_addr(context) += 2;
335         return sigtrap_handler(signal, siginfo, void_context);
336     }
337 #endif
338
339     fake_foreign_function_call(context);
340     lose("fake_foreign_call fell through");
341 }
342
343 void
344 arch_install_interrupt_handlers()
345 {
346     SHOW("entering arch_install_interrupt_handlers()");
347
348     /* Note: The old CMU CL code here used sigtrap_handler() to handle
349      * SIGILL as well as SIGTRAP. I couldn't see any reason to do
350      * things that way. So, I changed to separate handlers when
351      * debugging a problem on OpenBSD, where SBCL wasn't catching
352      * SIGILL properly, but was instead letting the process be
353      * terminated with an "Illegal instruction" output. If this change
354      * turns out to break something (maybe breakpoint handling on some
355      * OS I haven't tested on?) and we have to go back to the old CMU
356      * CL way, I hope there will at least be a comment to explain
357      * why.. -- WHN 2001-06-07 */
358 #ifndef LISP_FEATURE_WIN32
359     undoably_install_low_level_interrupt_handler(SIGILL , sigill_handler);
360     undoably_install_low_level_interrupt_handler(SIGTRAP, sigtrap_handler);
361 #endif
362
363     SHOW("returning from arch_install_interrupt_handlers()");
364 }
365 \f
366 /* This is implemented in assembly language and called from C: */
367 extern lispobj
368 call_into_lisp(lispobj fun, lispobj *args, int nargs);
369
370 /* These functions are an interface to the Lisp call-in facility.
371  * Since this is C we can know nothing about the calling environment.
372  * The control stack might be the C stack if called from the monitor
373  * or the Lisp stack if called as a result of an interrupt or maybe
374  * even a separate stack. The args are most likely on that stack but
375  * could be in registers depending on what the compiler likes. So we
376  * copy the args into a portable vector and let the assembly language
377  * call-in function figure it out. */
378
379 lispobj
380 funcall0(lispobj function)
381 {
382     lispobj *args = NULL;
383
384     FSHOW((stderr, "/entering funcall0(0x%lx)\n", (long)function));
385     return call_into_lisp(function, args, 0);
386 }
387 lispobj
388 funcall1(lispobj function, lispobj arg0)
389 {
390     lispobj args[1];
391     args[0] = arg0;
392     return call_into_lisp(function, args, 1);
393 }
394 lispobj
395 funcall2(lispobj function, lispobj arg0, lispobj arg1)
396 {
397     lispobj args[2];
398     args[0] = arg0;
399     args[1] = arg1;
400     return call_into_lisp(function, args, 2);
401 }
402 lispobj
403 funcall3(lispobj function, lispobj arg0, lispobj arg1, lispobj arg2)
404 {
405     lispobj args[3];
406     args[0] = arg0;
407     args[1] = arg1;
408     args[2] = arg2;
409     return call_into_lisp(function, args, 3);
410 }
411
412 #ifdef LISP_FEATURE_LINKAGE_TABLE
413 /* FIXME: It might be cleaner to generate these from the lisp side of
414  * things.
415  */
416
417 void
418 arch_write_linkage_table_jmp(char * reloc, void * fun)
419 {
420     /* Make JMP to function entry. JMP offset is calculated from next
421      * instruction.
422      */
423     long offset = (char *)fun - (reloc + 5);
424     int i;
425
426     *reloc++ = 0xe9;            /* opcode for JMP rel32 */
427     for (i = 0; i < 4; i++) {
428         *reloc++ = offset & 0xff;
429         offset >>= 8;
430     }
431
432     /* write a nop for good measure. */
433     *reloc = 0x90;
434 }
435
436 void
437 arch_write_linkage_table_ref(void * reloc, void * data)
438 {
439     *(unsigned long *)reloc = (unsigned long)data;
440 }
441
442 #endif