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