1.0.4.13: refactor trap handling
[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 (int *)(&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 restore_breakpoint_from_single_step(os_context_t * context)
213 {
214     /* fprintf(stderr,"* single step trap %x\n", single_stepping); */
215 #ifdef CANNOT_GET_TO_SINGLE_STEP_FLAG
216     /* Un-install single step helper instructions. */
217     *(single_stepping-3) = single_step_save1;
218     *(single_stepping-2) = single_step_save2;
219     *(single_stepping-1) = single_step_save3;
220 #else
221     *context_eflags_addr(context) &= ~0x100;
222 #endif
223     /* Re-install the breakpoint if possible. */
224     if (*os_context_pc_addr(context) == (int)single_stepping + 1) {
225         fprintf(stderr, "warning: couldn't reinstall breakpoint\n");
226     } else {
227         *((char *)single_stepping) = BREAKPOINT_INST;       /* x86 INT3 */
228         *((char *)single_stepping+1) = trap_Breakpoint;
229     }
230
231     single_stepping = NULL;
232     return;
233 }
234
235 void
236 arch_handle_breakpoint(os_context_t *context)
237 {
238     --*os_context_pc_addr(context);
239     handle_breakpoint(context);
240 }
241
242 void
243 arch_handle_fun_end_breakpoint(os_context_t *context)
244 {
245     --*os_context_pc_addr(context);
246     *os_context_pc_addr(context) =
247         (int)handle_fun_end_breakpoint(context);
248 }
249
250 void
251 arch_handle_single_step_trap(os_context_t *context, int trap)
252 {
253     arch_skip_instruction(context);
254     /* On x86 the fdefn / function is always in EAX, so we pass 0
255      * as the register_offset. */
256     handle_single_step_trap(context, trap, 0);
257 }
258
259 void
260 sigtrap_handler(int signal, siginfo_t *info, void *void_context)
261 {
262     os_context_t *context = (os_context_t*)void_context;
263     unsigned int trap;
264
265 #ifndef LISP_FEATURE_WIN32
266     /* On Windows this is done in the SE handler. */
267     if (single_stepping && (signal==SIGTRAP)) {
268         restore_breakpoint_from_single_step(context);
269         return;
270     }
271 #endif
272
273     /* This is just for info in case the monitor wants to print an
274      * approximation. */
275     current_control_stack_pointer =
276         (lispobj *)*os_context_sp_addr(context);
277
278     /* FIXME: CMUCL puts the float control restoration code here.
279        Thus, it seems to me that single-stepping won't restore the
280        float control.  Since SBCL currently doesn't support
281        single-stepping (as far as I can tell) this is somewhat moot,
282        but it might be worth either moving this code up or deleting
283        the single-stepping code entirely.  -- CSR, 2002-07-15 */
284 #if defined(LISP_FEATURE_LINUX) || defined(RESTORE_FP_CONTROL_FROM_CONTEXT)
285     os_restore_fp_control(context);
286 #endif
287
288
289 #ifdef LISP_FEATURE_SUNOS
290     /* For some reason the breakpoints that :ENCAPSULATE NIL tracing sets up
291      * cause a trace trap (i.e. processor single-stepping trap) on the following
292      * instruction on Solaris 10/x86. -- JES, 2006-04-07
293      */
294     if (info->si_code == TRAP_TRACE) {
295         lose("foo");
296         return;
297     }
298 #endif
299
300     /* On entry %eip points just after the INT3 byte and aims at the
301      * 'kind' value (eg trap_Cerror). For error-trap and Cerror-trap a
302      * number of bytes will follow, the first is the length of the byte
303      * arguments to follow. */
304     trap = *(unsigned char *)(*os_context_pc_addr(context));
305     if (!maybe_handle_trap(context, trap))
306         interrupt_handle_now(signal, info, context);
307 }
308
309 void
310 sigill_handler(int signal, siginfo_t *siginfo, void *void_context) {
311     os_context_t *context = (os_context_t*)void_context;
312
313     /* Triggering SIGTRAP using int3 is unreliable on OS X/x86, so
314      * we need to use illegal instructions for traps.
315      */
316 #if defined(LISP_FEATURE_DARWIN) && !defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
317     if (*((unsigned short *)*os_context_pc_addr(context)) == 0x0b0f) {
318         *os_context_pc_addr(context) += 2;
319         return sigtrap_handler(signal, siginfo, void_context);
320     }
321 #endif
322
323     fake_foreign_function_call(context);
324     lose("fake_foreign_call fell through");
325 }
326
327 void
328 arch_install_interrupt_handlers()
329 {
330     SHOW("entering arch_install_interrupt_handlers()");
331
332     /* Note: The old CMU CL code here used sigtrap_handler() to handle
333      * SIGILL as well as SIGTRAP. I couldn't see any reason to do
334      * things that way. So, I changed to separate handlers when
335      * debugging a problem on OpenBSD, where SBCL wasn't catching
336      * SIGILL properly, but was instead letting the process be
337      * terminated with an "Illegal instruction" output. If this change
338      * turns out to break something (maybe breakpoint handling on some
339      * OS I haven't tested on?) and we have to go back to the old CMU
340      * CL way, I hope there will at least be a comment to explain
341      * why.. -- WHN 2001-06-07 */
342 #if !defined(LISP_FEATURE_WIN32) && !defined(LISP_FEATURE_MACH_EXCEPTION_HANDLER)
343     undoably_install_low_level_interrupt_handler(SIGILL , sigill_handler);
344     undoably_install_low_level_interrupt_handler(SIGTRAP, sigtrap_handler);
345 #endif
346
347     SHOW("returning from arch_install_interrupt_handlers()");
348 }
349 \f
350 /* This is implemented in assembly language and called from C: */
351 extern lispobj
352 call_into_lisp(lispobj fun, lispobj *args, int nargs);
353
354 /* These functions are an interface to the Lisp call-in facility.
355  * Since this is C we can know nothing about the calling environment.
356  * The control stack might be the C stack if called from the monitor
357  * or the Lisp stack if called as a result of an interrupt or maybe
358  * even a separate stack. The args are most likely on that stack but
359  * could be in registers depending on what the compiler likes. So we
360  * copy the args into a portable vector and let the assembly language
361  * call-in function figure it out. */
362
363 lispobj
364 funcall0(lispobj function)
365 {
366     lispobj *args = NULL;
367
368     FSHOW((stderr, "/entering funcall0(0x%lx)\n", (long)function));
369     return call_into_lisp(function, args, 0);
370 }
371 lispobj
372 funcall1(lispobj function, lispobj arg0)
373 {
374     lispobj args[1];
375     args[0] = arg0;
376     return call_into_lisp(function, args, 1);
377 }
378 lispobj
379 funcall2(lispobj function, lispobj arg0, lispobj arg1)
380 {
381     lispobj args[2];
382     args[0] = arg0;
383     args[1] = arg1;
384     return call_into_lisp(function, args, 2);
385 }
386 lispobj
387 funcall3(lispobj function, lispobj arg0, lispobj arg1, lispobj arg2)
388 {
389     lispobj args[3];
390     args[0] = arg0;
391     args[1] = arg1;
392     args[2] = arg2;
393     return call_into_lisp(function, args, 3);
394 }
395
396 #ifdef LISP_FEATURE_LINKAGE_TABLE
397 /* FIXME: It might be cleaner to generate these from the lisp side of
398  * things.
399  */
400
401 void
402 arch_write_linkage_table_jmp(char * reloc, void * fun)
403 {
404     /* Make JMP to function entry. JMP offset is calculated from next
405      * instruction.
406      */
407     long offset = (char *)fun - (reloc + 5);
408     int i;
409
410     *reloc++ = 0xe9;            /* opcode for JMP rel32 */
411     for (i = 0; i < 4; i++) {
412         *reloc++ = offset & 0xff;
413         offset >>= 8;
414     }
415
416     /* write a nop for good measure. */
417     *reloc = 0x90;
418 }
419
420 void
421 arch_write_linkage_table_ref(void * reloc, void * data)
422 {
423     *(unsigned long *)reloc = (unsigned long)data;
424 }
425
426 #endif