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